Odd Question about if-else-if statement

So today I've been coding a small game, and I was writing the movement by pressing keys, my question is about the stopping when you release a key. This is was I have.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
        if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
	{
		_velocityX = -200.0f;
	}
	else
	{
		_velocityX = 0.0f;
	}
	if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
	{
		_velocityX = 200.0f;
	}

	if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
	{
		_velocityY = -200.0f;
	}
	else
	{
		_velocityY = 0.0f;
	}
	if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
	{
		_velocityY = 200.0f;
	}


This works. What my question would be is that why does this work? Wouldn't you need the else statements after the second if statement for each x and y? because when I tried that it didn't work. but this does. I'm just curious why.
Last edited on
Well, I'm guessing this snippet of code is located in some callback function.
Let's say that you press and hold the right arrow key. Your velocityX is now 200.0f units of whatever.
You let go of the right arrow key, and your velocityX is now zero. It's zero, because the next time the callback function gets called (which, I'm assuming is every other frame), it's very likely that you're not pressing left. Because you're not pressing left, the else blocks get executed and set the velocity to zero.

If you were to put an else after each if, that wouldn't work for the following reason:

Let's say you're pressing the up arrow key. Your velocityY is now -200.0f, but then right after you're checking if you're going down, which you're not, so velocityY gets set to zero.

You can solve this problem by using else if.
Last edited on
Topic archived. No new replies allowed.