snake example: Don't allow player to attempt to move backwards.

This commit is contained in:
SeanOMik 2021-04-03 22:30:41 -05:00
parent 94cbd111e8
commit 283601200d
No known key found for this signature in database
GPG Key ID: CA09E5BE1F32728A
1 changed files with 21 additions and 8 deletions

View File

@ -44,6 +44,10 @@ private:
const sf::Vector2f& entity_pos; const sf::Vector2f& entity_pos;
simpleengine::Game& game; simpleengine::Game& game;
bool IsStill() {
return movement_direction.x == 0 && movement_direction.y == 0;
}
public: public:
explicit SnakeMovementComponent(simpleengine::Entity& owning_entity, float movement_speed, const sf::Vector2u& window_size, simpleengine::Game& game) explicit SnakeMovementComponent(simpleengine::Entity& owning_entity, float movement_speed, const sf::Vector2u& window_size, simpleengine::Game& game)
: simpleengine::Component(owning_entity), movement_speed(movement_speed), window_size(window_size), : simpleengine::Component(owning_entity), movement_speed(movement_speed), window_size(window_size),
@ -59,20 +63,29 @@ public:
switch (key) { switch (key) {
case sf::Keyboard::W: case sf::Keyboard::W:
movement_direction.x = 0; // Make sure we're not trying to move the opposite direction.
movement_direction.y = -15; if (IsStill() || movement_direction.x != 0 && movement_direction.y != 15) {
movement_direction.x = 0;
movement_direction.y = -15;
}
break; break;
case sf::Keyboard::A: case sf::Keyboard::A:
movement_direction.x = -15; if (IsStill() || movement_direction.x != 15 && movement_direction.y != 0) {
movement_direction.y = 0; movement_direction.x = -15;
movement_direction.y = 0;
}
break; break;
case sf::Keyboard::S: case sf::Keyboard::S:
movement_direction.x = 0; if (IsStill() || movement_direction.x != 0 && movement_direction.y != 15) {
movement_direction.y = 15; movement_direction.x = 0;
movement_direction.y = 15;
}
break; break;
case sf::Keyboard::D: case sf::Keyboard::D:
movement_direction.x = 15; if (IsStill() || movement_direction.x != -15 && movement_direction.y != 0) {
movement_direction.y = 0; movement_direction.x = 15;
movement_direction.y = 0;
}
break; break;
case sf::Keyboard::Space: case sf::Keyboard::Space:
movement_direction.x = 0; movement_direction.x = 0;