Skip to content
Download

Move with the keyboard

You want an object to move while the player holds the arrow keys.

#include <brasa/brasa.hpp>
using namespace brasa;
class Player : public Entity {
public:
void onUpdate() override {
const float speed = 2.0f; // pixels per step
if (held(Key::Left) || held(Key::A)) x -= speed;
if (held(Key::Right) || held(Key::D)) x += speed;
if (held(Key::Up) || held(Key::W)) y -= speed;
if (held(Key::Down) || held(Key::S)) y += speed;
}
};
BRASA_ENTITY(Player);
  • onUpdate runs 60 times per second. Each time, the code checks the keyboard.
  • held(Key::Left) is true while the key is held down.
  • x grows to the right and y grows downwards. That’s why “up” is y -= speed.
  • || means or: the arrow and the letter do the same thing.

Move diagonally at the same speed. Adding the two directions, the diagonal ends up faster. Keep the direction in dx/dy and fix it with 0.7071 (that’s how it is in the tutorial):

if (dx != 0.0f && dy != 0.0f) { dx *= 0.7071f; dy *= 0.7071f; }

Don’t go through walls. Mark the wall object as Sólido (solid) in the Inspector and move with moveAndStop, which stops when it touches a solid:

float dx = 0, dy = 0;
if (held(Key::Left)) dx -= 2;
if (held(Key::Right)) dx += 2;
moveAndStop(dx, dy);

One action per tap. To jump or open a menu, use pressed, which is true only on the step when the key was pressed:

if (pressed(Key::Space)) vspeed = -6; // jump