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;
simpleengine::Game& game;
bool IsStill() {
return movement_direction.x == 0 && movement_direction.y == 0;
}
public:
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),
@ -59,20 +63,29 @@ public:
switch (key) {
case sf::Keyboard::W:
// Make sure we're not trying to move the opposite direction.
if (IsStill() || movement_direction.x != 0 && movement_direction.y != 15) {
movement_direction.x = 0;
movement_direction.y = -15;
}
break;
case sf::Keyboard::A:
if (IsStill() || movement_direction.x != 15 && movement_direction.y != 0) {
movement_direction.x = -15;
movement_direction.y = 0;
}
break;
case sf::Keyboard::S:
if (IsStill() || movement_direction.x != 0 && movement_direction.y != 15) {
movement_direction.x = 0;
movement_direction.y = 15;
}
break;
case sf::Keyboard::D:
if (IsStill() || movement_direction.x != -15 && movement_direction.y != 0) {
movement_direction.x = 15;
movement_direction.y = 0;
}
break;
case sf::Keyboard::Space:
movement_direction.x = 0;