Skip to content
Download

Platformer

You want a character that falls, lands on the floor, jumps and doesn’t go through walls.

  1. On the floor and wall object, check Sólido (solid) in the Inspector. Or paint the floor with solid tiles: see Scenery with tiles.
  2. On the player object, in the Física (physics) section, set Gravidade (gravity) to 0.25 and Queda máxima (maximum fall) to 4.5.

Gravity pulls the player down on every step, and the maximum fall keeps it from falling faster and faster.

void Player::onUpdate() {
hspeed = axis("esquerda", "direita") * 1.5f;
if (pressed("pular") && onGround()) vspeed = -4.5f;
moveAndStop();
}
  • axis("esquerda", "direita") gives the direction: -1, 0 or 1. 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.5f throws the player upward (y grows downward). Gravity takes care of bringing it back.
  • moveAndStop() applies gravity and moves by hspeed and vspeed, stopping when it touches a solid. Call it once per step.

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;