Platformer
You want a character that falls, lands on the floor, jumps and doesn’t go through walls.
In the editor
Section titled “In the editor”- On the floor and wall object, check Sólido (solid) in the Inspector. Or paint the floor with solid tiles: see Scenery with tiles.
- On the player object, in the Física (physics) section, set Gravidade (gravity) to
0.25and Queda máxima (maximum fall) to4.5.
Gravity pulls the player down on every step, and the maximum fall keeps it from falling faster and faster.
In the code
Section titled “In the code”void Player::onUpdate() { hspeed = axis("esquerda", "direita") * 1.5f; if (pressed("pular") && onGround()) vspeed = -4.5f; moveAndStop();}How it works
Section titled “How it works”axis("esquerda", "direita")gives the direction:-1,0or1. See actions.onGround()is true when there is a solid 1 pixel below the player. Without this check, it would jump in mid-air.vspeed = -4.5fthrows the player upward (ygrows downward). Gravity takes care of bringing it back.moveAndStop()applies gravity and moves byhspeedandvspeed, stopping when it touches a solid. Call it once per step.
Variations
Section titled “Variations”Face the side it is walking to. flipX mirrors the drawing and the collision box, without touching the scale:
if (hspeed != 0) flipX = hspeed < 0;An enemy that walks back and forth. After moveAndStop(), hitWall() tells whether it hit a wall:
void Enemy::onUpdate() { hspeed = flipX ? -0.5f : 0.5f; moveAndStop(); if (hitWall()) flipX = !flipX;}Do something on landing. hitFloor() is true on the step the player hit the floor; hitCeiling(), when it bumped its head on the ceiling:
moveAndStop();if (hitFloor()) Audio::play("pouso");Keep the collision box from changing with the animation. If the running sprite is wider than the standing one, the player can get stuck in a wall when the animation changes. In the object’s Inspector, choose a sprite under Máscara (mask): the collision then always uses its box.
A lower jump when the button is released.
if (released("pular") && vspeed < 0) vspeed *= 0.5f;See also
Section titled “See also”- Movement: gravity, friction and
moveAndStop. - Collisions.
- Camera following the player.
