Материал из Скретч Вики
- Эта участник — о базовом платформере. Для руководства по более продвинутой физике см. Продвинутая физика платформера. Для скроллинговых платформеров см. Как сделать скроллинговый платформер.
Платформер — это симуляция реальных физических явлений, происходящих в реальной жизни. Объекты падают, двигаются, скользят, прыгают и отскакивают, а платформер объединяет эти свойства в игру, в которой вы управляете персонажем и пытаетесь продвинуть его к цели. Данное руководство объяснит, как сделать базовый платформер.
Создание спрайта
Спрайт платформера — это аватар, управляемый игроком. Его внешний вид может немного повлиять на игровой процесс, в зависимости от углов и размера его костюмов. Например, персонаж не должен спастись от падения из-за того, что ободок его шляпы зацепился за край обрыва. Спрайты, которые анимируются с помощью множества смен костюмов, ещё более сложны, поскольку меняющийся костюм может затянуться в землю и застрять.
Ниже приведён пример простого скрипта для спрайта платформера. Он использует две переменные:
- «Скорость X» хранит значение, представляющее горизонтальную скорость спрайта. Необходимо отметить галочку «Только для этого спрайта» in the creation dialog. This means (i) the variable can only be changed by scripts in the same sprite, (ii) the variable name does not needlessly clutter the variable pane of other sprites, and (iii) the same variable name may be used in other sprites without causing conflicts.
- "Gravity" stores a value reflecting the strength of the sprite's tendency to fall. In this example it is set as a negative number because moving a sprite downwards requires making the value of its Y position smaller. "Gravity" need not be set as a local variable; a realistic game would subject all its characters to the same gravitational force.[1]
when green flag clicked set [gravity v] to [-5] forever if <key (left arrow v) pressed?> then // using "else" saves processing later ifs unnecessary set [x velocity v] to [-4] else if <key (right arrow v) pressed?> then set [x velocity v] to [4] else set [x velocity v] to [0] // no arrow keys means no movement end end if <not <touching (ground sprite v)?>> then // sprite falls till touching ground change y by (gravity) end change x by (x velocity) end
Walking
Here is the code for platformer walking.
when green flag clicked forever if <key (a v) pressed?> then change [velocity v] by (-1) end if <key (d v) pressed?> then change [velocity v] by (1) end speed cap (5)::custom change x by (velocity)
define speed cap (max speed) if <(velocity) > (max speed)> then set [velocity v] to (max speed) end if <(velocity) < ((max speed) * (-1))> then set [velocity v] to ((max speed) * (-1)) end set [velocity v] to ((velocity)*(0.9))
Jumping
To jump, use this code:
when green flag clicked forever if <key (up arrow v) pressed?> then // the jumping key repeat [10] change y by [15] end repeat until <touching (ground sprite v)> change y by [-5] end end end
Making Levels
Colors can be used in a platform for detection of the end of a level or an object which sends one back to the beginning of the level. For this tutorial, assume the following:
- The character sprite performing the physics is named "Player"
- Black is the color of the platform, or ground and walls, in which the character cannot pass through
- Red is the color that sends one back to the beginning of the level they are on
- Yellow is the color which must be reached to move on to the next level
- Backgrounds are used as levels instead of sprites
- Scrolling is not incorporated
The shapes do not need to be geometric, but can be organic, meaning an unordinary, inconsistent structure. There can be curvature to the various colors and platforms, which can be used to create diverse, numerous levels. The following image displays an example of some organic shapes being used:
When the levels are finished, add the following script to the "Player" sprite:
when gf clicked forever if <touching color [#FF0000]?> then//if in contact with the color red go to x:(-180) y:(-47) // relocate to the start end if <touching color [#FFFF00]?> then//if at the end of a level go to x:(-180) y:(-47) // relocate to the start switch backdrop to (next backdrop v)// next level end
The scripts within the "forever" loop can be merged with the larger physics script shown farther above. Merging the scripts reduces the amount of conditions being checked at once and can possibly make the project more uniform and orderly, meaning the "Player" makes each movement and then checks for the conditions instead of the conditions possibly being checked during the sprite's movement.
![]() |
A condition is a statement that is checked for a true/false response. In the example above, when the sprite checks if it's touching a color, it's checking a condition. |
Then add the following script to any sprite:
when gf clicked switch backdrop to (level 1 v)//begin with the first level
Lastly, add the following script to the "Player" sprite:
when gf clicked show wait until <([backdrop # v] of [Stage v]) = (amount of backdrops)>//wait until the last level is reached stop [all v]
Making the Win Background
Last of all, comes the win background. After finishing all the levels in the platformer, something would come up that says something like "You Win!". Put it as the last costume in the sprite/background. It can be some text in a basic white background saying "You win" or the art can be complex.
See Also
- Advanced Platformer Physics — a tutorial on how to make a more realistic platformer
- Scrolling Platformer Tutorial — a tutorial on how to make a scrolling platformer
- Creating a Final Boss Sprite — a tutorial on how to add a final boss sprite to a platformer