Handling sprite animation with switch

I'm currently handling sprite animation with a switch that changes the animation based on the directional arrow pressed. I'm using an SDL_Event switch to do so. The problem is lets say I hold down left, then while keeping left pressed i press right, then I let go of right and left is still pressed.

This is what happens.

Press left - left running animation plays

While still holding left I pres right - right animation plays

I let go of right and have left still pressed - default animation plays(idle)


Is it better to use a while loop or an if statement for this? What would you guys recommend?

A switch is preferable I think because it expresses what you're doing better: you're taking different actions based on the value of a single expression.

To solve your problem, you need to look at the current state of the keys. So the logic should be something like:
1
2
3
4
wait for key up or key down.
switch(getKeyState()) {
...
}


Inside getKeyState() you will check to see which (if any) arrow keys are down. Decide what should happen if multiple keys are pressed before you start writing the code.
Thanks, I'll look into that and let you know the solution I come to and/or any questions that come up
I came up with a solution and it looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
if (keyState[SDL_SCANCODE_RIGHT])
		{
			facingLeft = false;
			animation = runRightTexture;
			sprite = (ticks / 100) % 6;
			if (SDL_GetTicks() > time + 4)
			{
				++xCoord;
				time = SDL_GetTicks();
			}
		}
		else if (keyState[SDL_SCANCODE_LEFT])
		{
			facingLeft = true;
			animation = runLeftTexture;
			sprite = (ticks / 100) % 6;
			if (SDL_GetTicks() > time + 4)
			{
				--xCoord;
				time = SDL_GetTicks();
			}
		}
Topic archived. No new replies allowed.