Jump to content

  • Log In with Google      Sign In   
  • Create Account


[SDL] Moving right and left


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
3 replies to this topic

#1 munchor   Members   -  Reputation: 101

Like
0Likes
Like

Posted 19 May 2012 - 12:08 PM


  while (running) {
	SDL_PollEvent(&event);

	if (event.type == SDL_QUIT) {
	  SDL_Quit();
	  return 0;
	} else if (event.type == SDL_KEYDOWN) {
	  int key_code = event.key.keysym.sym;

	  if (key_code == SDLK_ESCAPE) {
		SDL_Quit();
		return 0;
	  }

	  if (key_code == SDLK_RIGHT && player.x < SCREEN_WIDTH - 5 - player.width) player.x++;
	  if (key_code == SDLK_LEFT && player.x > 0 + 5) player.x--;
	}

	draw_rect(screen, player.x, player.y, player.width, player.height, 0xFF);

	SDL_Flip(screen);
	clear_screen(screen, 0, 0, 0);
  }

This is my main code loop, and it's where I make my player move right or left. However, when I press right, and then release right and press left (fairly quick movement) again, the player will move a bit to the left a bit and then stops, requiring me to release LEFT and repress it to keep moving.

The player gets stuck all the time, it's hard to explain what's going on.

Any ideas on how can I fix this? Thank you in advance.

Edited by munchor, 19 May 2012 - 12:51 PM.


Sponsor:

#2 Servant of the Lord   Crossbones+   -  Reputation: 17144

Like
0Likes
Like

Posted 19 May 2012 - 12:54 PM

There are three (minor!) mistakes in your code that are working together to produce the buggy results.

The first mistake: You aren't separating out *reading input* from *updating the game*. You really should be.
SDL doesn't send you KEYDOWN events every frame, you just receive it once when the key first goes down... so your current code (If it weren't for other bugs working with it) would only move the character once each keypress, which is not what you want (Keypress -> Move 5 pixels. Keypress -> Move 5 pixels). What you want is (While the keypress is down, keep moving five pixels each frame*).

So you need to separate your "Update every frame" code from your "Read and react to input" code. This means, check for input first (if there is input), at the top of the "while (running)" loop, based off of the input change the internal state of the game (PlayerMovingLeft = true, PlayerMovingRight = false), and regardless of whether there is input or not, every frame react to the internal state of the game ( if(PlayerMovingLeft) {...move the player five pixels...} ).

*Actually, what you really want is, "Each frame, depending on how much time is passed, move (PER_SECOND_MOVEMENT * fractionOfASecondThatPassed), but that's just complicating your current problem, and you can always learn about that some other time.

So that's the first issue, and your code should now look like this:
bool playerMovingLeft = false;
bool playerMovingRight = false;
while (running)
{
	//-------------------------------------
	//Check input, and change the internal state of the game.
	//-------------------------------------
  
	SDL_PollEvent(&event);
  
	if (event.type == SDL_QUIT)
	{
		SDL_Quit();
		return 0;
	}
	else if (event.type == SDL_KEYDOWN)
	{
		int key_code = event.key.keysym.sym;
	  
		if (key_code == SDLK_ESCAPE)
		{
			SDL_Quit();
			return 0;
		}
	  
		if (key_code == SDLK_RIGHT) playerMovingLeft = true;
		if (key_code == SDLK_LEFT) playerMovingRight = true;
	}
	else if (event.type == SDL_KEYUP)
	{
		int key_code = event.key.keysym.sym;
	  
		if (key_code == SDLK_RIGHT) playerMovingLeft = false;
		if (key_code == SDLK_LEFT) playerMovingRight = false;
	}
  
	//-------------------------------------
	//Update the game data, based off of the internal state of the game.
	//-------------------------------------
  
	if (playerMovingLeft == true && player.x < SCREEN_WIDTH - 5 - player.width) player.x++;
	if (playerMovingRight == true && player.x > 0 + 5) player.x--;
  
	//-------------------------------------
	//Draw the game, based off of the game data.
	//-------------------------------------
  
	draw_rect(screen, player.x, player.y, player.width, player.height, 0xFF);
  
	SDL_Flip(screen);
	clear_screen(screen, 0, 0, 0);
}


The second issue, is that you aren't checking the return value of SDL_PollEvent(). It returns true if there is input, otherwise it returns false and you're not supposed to use the 'event' variable for anything.


So your entire input should be wrapped in an if(...) statement, like this:

SDL_Event event;[/left]
	bool gotSomeEventsToProcess = SDL_PollEvent(&event);
	if( gotSomeEventsToProcess ) //Or just: if( SDL_PollEvent(&event) )
	{
		if (event.type == SDL_QUIT)
		{
			...
		}
		else if (event.type == SDL_KEYDOWN)
		{
			...
		}
		else if (event.type == SDL_KEYUP)
		{
			...
		}
	}


The third issue is this: You might get more than one input event each frame! So the "if( SDL_PollEvent(&event) )" should actually be a "while( SDL_PollEvent(&event) )", otherwise if you get too many input events in one frame, it'll wait for the next frame before dealing with them, and your game will eventually start lagging where you click on something and it only processes the click many frames later.

So your actual code should look like this:
bool playerMovingLeft = false;
bool playerMovingRight = false;

while (running)
{
	//-------------------------------------
	//Check input, and change the internal state of the game.
	//-------------------------------------

	SDL_Event event;
	while( SDL_PollEvent(&event) )
	{
		if (event.type == SDL_QUIT)
		{
			SDL_Quit();
			return 0;
		}
		else if (event.type == SDL_KEYDOWN)
		{
			int key_code = event.key.keysym.sym;

			if (key_code == SDLK_ESCAPE)
			{
				SDL_Quit();
				return 0;
			}

			if (key_code == SDLK_RIGHT) playerMovingLeft = true;
			if (key_code == SDLK_LEFT) playerMovingRight = true;
		}
		else if (event.type == SDL_KEYUP)
		{
			int key_code = event.key.keysym.sym;

			if (key_code == SDLK_RIGHT) playerMovingLeft = false;
			if (key_code == SDLK_LEFT) playerMovingRight = false;
		}
	}

	//-------------------------------------
	//Update the game data, based off of the internal state of the game.
	//-------------------------------------

	if (playerMovingLeft == true && player.x < SCREEN_WIDTH - 5 - player.width) player.x++;
	if (playerMovingRight == true && player.x > 0 + 5) player.x--;

	//-------------------------------------
	//Draw the game, based off of the game data.
	//-------------------------------------

	draw_rect(screen, player.x, player.y, player.width, player.height, 0xFF);

	SDL_Flip(screen);
	clear_screen(screen, 0, 0, 0);
}

This should completely fix your problem - these are common mistakes, ones which have burned me a couple of times when starting out. Posted Image

You might even want to break up your "drawing" code, your "input code", and your "update" code into three separate functions for organization, but that's up to your own preferences. Good luck with your game!

Edited by Servant of the Lord, 19 May 2012 - 01:45 PM.

It's perfectly fine to abbreviate my username to 'Servant' rather than copy+pasting it all the time.

[Fly with me on Twitter] [Google+] [My broken website]

All glory be to the Man at the right hand... On David's throne the King will reign, and the Government will rest upon His shoulders. All the earth will see the salvation of God.                                                                                                                                                       [Need free cloud storage? I personally like DropBox]

Of Stranger Flames - [indie turn-based rpg set in a para-historical French colony] | Indie RPG development journal


#3 Servant of the Lord   Crossbones+   -  Reputation: 17144

Like
0Likes
Like

Posted 19 May 2012 - 01:00 PM

You can also use SDL_GetKeyState() to read keypresses, like this:

Uint8 *keystates = SDL_GetKeyState(NULL);
if (keystate[SDLK_LEFT] && player.x < SCREEN_WIDTH - 5 - player.width) player.x++;
if (keystate[SDLK_RIGHT] && player.x > 0 + 5) player.x--;

...and thus get rid of the 'playerMovingLeft' and 'playerMovingRight' variables, since SDL does that internally, making your code cleaner. But it's important that you understood what is actually happening before using SDL_GetKeyState() as a magic bullet.

Edited by Servant of the Lord, 19 May 2012 - 01:09 PM.

It's perfectly fine to abbreviate my username to 'Servant' rather than copy+pasting it all the time.

[Fly with me on Twitter] [Google+] [My broken website]

All glory be to the Man at the right hand... On David's throne the King will reign, and the Government will rest upon His shoulders. All the earth will see the salvation of God.                                                                                                                                                       [Need free cloud storage? I personally like DropBox]

Of Stranger Flames - [indie turn-based rpg set in a para-historical French colony] | Indie RPG development journal


#4 munchor   Members   -  Reputation: 101

Like
0Likes
Like

Posted 19 May 2012 - 01:57 PM

Servant Of The Lord, I actually read what you said twice, very nice explanation, I shall implement it right away and see how it works :)




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS