Moving a player while holding down a key.

Started by
20 comments, last by MylesEvans 11 years, 3 months ago

I can currently move my player over by tapping the key. If I press once moves X units. If I hit twice 2X units, etc.

I want to be able to move the player by holding down the key and then when I let the key up the player stops moving.

This is my current code.


void handleKeys(  )
{
    
	

    if (event.type == SDL_KEYDOWN)
	                 {
	                    switch( event.key.keysym.sym )
	                    {

						       
	                            case SDLK_w:
	                                PBbaseoffY  = PBbaseoffY + 10;
	                                 break;
	                            case SDLK_s:
	                                 PBbaseoffY = PBbaseoffY - 10;
	                                 break;
	                            case SDLK_a:
	                                 PBbaseoffX = PBbaseoffX - 10;
	                                 break;
	                            case SDLK_d:
	                                 PBbaseoffX = PBbaseoffX + 10;
	                                 break;
								

	                          
	                    
	                 }
	                 

	}
 


}

I works fine but like I said I want to be able to hold it down to move.

Advertisement
some ideas here:
http://gamedev.stackexchange.com/questions/19571/how-can-i-process-continuously-held-keys-with-sdl
http://www.cplusplus.com/forum/general/61263/

also, this might belong in Beginners section

http://content.gpwiki.org/index.php/SDL:Tutorials:Practical_Keyboard_Input

http://content.gpwiki.org/index.php/SDL:Tutorials:Practical_Keyboard_Input

Ok, where should I put this? Should I put it inside main() which currently looks like this?


while( quit == false )
	{
        //Start the frame timer
        fps.start();

        //While there are events to handle
		while( SDL_PollEvent( &event ) )
		{
			if( event.type == SDL_QUIT )
			{
                quit = true;
            }
            else if( event.type == SDL_KEYDOWN )
            {
                //Handle keypress with current mouse position
                int x = 0, y = 0;
                SDL_GetMouseState( &x, &y );
                handleKeys( event.key.keysym.unicode, x, y );
            }
		}

Or should I put that code from your link into the handlekeys() function? I tried putting it into main and it compiles but only for a second before it exits the code.

Please do not c&p code that you find laying around. The skeleton man will eat you.

Read through the article completely and if there's anything about the concept that you don't get then ask questions until you do get it and can implement it yourself with confidence.

void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.

I understand the code, but I just cant get it to work properly. I can get it to work somewhat by making a function called HeldKeys() (That has the code in the link you gave me adapted for my project of course) and putting the call to it after the render function that draws the players body. Its outside of the


while( SDL_PollEvent( &event ) )

which might explain why when I do it like this I can exit the program by Xing out because thats being checked for inside the while (SDL_PollEvent(( &event)).

The code looks like this.

  1. while( quit == false )
  2. {
  3. //Start the frame timer
  4. fps.start();
  5. //While there are events to handle
  6. while( SDL_PollEvent( &event ) )
  7. {
  8. if( event.type == SDL_QUIT )
  9. {
  10. quit = true;
  11. }
  12. else if( event.type == SDL_KEYDOWN )
  13. {
  14. //Handle keypress with current mouse position
  15. int x = 0, y = 0;
  16. SDL_GetMouseState( &x, &y );
  17. handleKeys( event.key.keysym.unicode, x, y );
  18. }
  19. }

Render();

HeldKeys();

If I put the HeldKeys() function call inside the while( SDL_PollEvent( &event ) ) It wont work. If I put it inside the handleKeys() it wont work. Only if I put it after the Render(); will it work but then I cant X out the program or add any events to the handlekeys() function because they wont work.

I didn't read through all the code, but here's how you want to handle input.

Have 4 boolean variables, leftKeyPressed, rightKeyPressed, upKeyPressed, downKeyPressed, or whatever you want to name them. Set them all to false.

When the player presses down the key, switch the appropriate boolean to true.

When the player releases the key, switch the appropriate boolean to false.


Then in your game loop, check


if (leftKeyPressed)
{
  //Perform movement here
}

I didn't read through all the code, but here's how you want to handle input.

Have 4 boolean variables, leftKeyPressed, rightKeyPressed, upKeyPressed, downKeyPressed, or whatever you want to name them. Set them all to false.

When the player presses down the key, switch the appropriate boolean to true.

When the player releases the key, switch the appropriate boolean to false.


Then in your game loop, check


if (leftKeyPressed)
{
  //Perform movement here
}

Spot on!

I use SFML, however the topic is universal. Another way would be saying:


if (KeyBoard::IsKeyDown(Key::Left))
{
  //Move Player
}

In your game loop. Checking if the key is simply down rather than polling for an event would suffice, and reduce the amount of memory needed.

Although, Memory isn't very important, and four bits worth of variables (Booleans are a single bit) Isn't very important, so I'd go with AdrianC's system, mainly because it seems more clear. I hope you fix your problem, Cheers :)!

I'm a game programmer and computer science ninja !

Here's my 2D RPG-Ish Platformer Programmed in Python + Pygame, with a Custom Level Editor and Rendering System!

Here's my Custom IDE / Debugger Programmed in Pure Python and Designed from the Ground Up for Programming Education!

Want to ask about Python, Flask, wxPython, Pygame, C++, HTML5, CSS3, Javascript, jQuery, C++, Vimscript, SFML 1.6 / 2.0, or anything else? Recruiting for a game development team and need a passionate programmer? Just want to talk about programming? Email me here:

hobohm.business@gmail.com

or Personal-Message me on here !

I didn't read through all the code, but here's how you want to handle input.

Have 4 boolean variables, leftKeyPressed, rightKeyPressed, upKeyPressed, downKeyPressed, or whatever you want to name them. Set them all to false.

When the player presses down the key, switch the appropriate boolean to true.

When the player releases the key, switch the appropriate boolean to false.


Then in your game loop, check


if (leftKeyPressed)
{
  //Perform movement here
}

This worked much better! Those issues I described above are non-existent now, but I do have what I hop is a minor problem now. I made the boolean variables and set them to false. I can detect when a key is pressed and move the player, but It seems theres a problem detecting when the key is up. I can just hit the key and the player will move until I hit another key. It wont stop when I release the key.

Here is my code for checking if a key is down/up.


void handleKeys( )
{
     UpKeyHeld = false; 
	 DownKeyHeld = false;
	 LeftKeyHeld = false;
	 RightKeyHeld = false;

	 switch(event.type){
    case SDL_KEYDOWN:
      switch(event.key.keysym.sym){
        case SDLK_w:
          UpKeyHeld = true;
          break;
		  case SDLK_s:
          DownKeyHeld = true;
          break;
		  case SDLK_a:
          LeftKeyHeld = true;
          break;
		  case SDLK_d:
          RightKeyHeld = true;
          break;
        
        default:
          break;
       }
       break;
    case SDL_KEYUP:
      switch(event.key.keysym.sym){
         case SDLK_w:
          UpKeyHeld = false;
          break;
		  case SDLK_s:
          DownKeyHeld = false;
          break;
		  case SDLK_a:
          LeftKeyHeld = false;
          break;
		  case SDLK_d:
          RightKeyHeld = false;
          break;
        
        default:
          break;
      }
	 }
}

and the I call a function to update the players position.


void PlayerVel ()
{
	if (  UpKeyHeld == true   )
	  {
		PBbaseoffY += -1;  
	  }
	else if (  DownKeyHeld == true   )
	  {
		PBbaseoffY += 1;  
	  }
	else if (  LeftKeyHeld == true   )
	  {
		PBbaseoffX += -1;  
	  }
	else if (  RightKeyHeld == true   )
	  {
		PBbaseoffX += 1;  
	  }
	
}

First, don't set all your bools to false at the start of handleKeys(). That defeats the purpose of checking to see if they were released. I'm really surprised you're not getting the opposite problem. The way the code is written there I'd expect your guy to only move on the frame when the key was initially pressed.

Can you confirm that SDL_KEYUP messages are being generated when a key is released?

void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.

This topic is closed to new replies.

Advertisement