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);How it works
Section titled “How it works”onUpdateruns 60 times per second. Each time, the code checks the keyboard.held(Key::Left)is true while the key is held down.xgrows to the right andygrows downwards. That’s why “up” isy -= speed.||means or: the arrow and the letter do the same thing.
Variations
Section titled “Variations”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; // jumpSee also
Section titled “See also”- Input: all the keys and the mouse.
- Keyboard and gamepad with actions: the same code for the keyboard and the gamepad.
- Movement: speed, direction, gravity and
moveAndStop. - 2. The ship, in the tutorial.
