Skip to main content
GameDev.net gamedev.net
🔒 Locked

Moving a player while holding down a key.

Started by MylesEvans Dec 26, 2012 at 11:55 PM 20 replies 3.8k views
Original Post
MylesEvans
MylesEvans

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.

MylesEvans
MylesEvans
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.

Khatharr
Khatharr

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.
MylesEvans
MylesEvans

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.

AdrianC
AdrianC

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
}
superman3275
superman3275

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 :)!

MylesEvans
MylesEvans

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;  
	  }
	
}
Khatharr
Khatharr

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.
MylesEvans
MylesEvans
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?

Well, thats the problem. I don't think SDL_KEYUP is working because when I press the key the player starts moving, but when I let go of it the player is still moving. I need to be able to determine when the key is released so I can stop the player.

Khatharr
Khatharr

So can you test to see if that's what's causing the problem? Just put in a line before your call to handleKeys() that pops a message box or something when an SDL_KEYUP event happens and then start the program and hammer a couple keys to see if the message appears.

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.
MylesEvans
MylesEvans
So can you test to see if that's what's causing the problem? Just put in a line before your call to handleKeys() that pops a message box or something when an SDL_KEYUP event happens and then start the program and hammer a couple keys to see if the message appears.

I did something similar. I drew a square in the case after the KEYUP (where it supposed to make the boolean false again).

No square was drawn upon releasing the key so I'm pretty sure that is where the problem lies. Its not registering the KEYUP which is why my character keeps going after I let go of the key.

Khatharr
Khatharr

Are you testing it at the point of event generation (where SDL produces the event) or after some logic has happened?

If you're testing it at the point of event generation then there's either something wrong with your SDL or else something needs to happen in order to allow that event to be generated (I don't use SDL, so I dunno). Otherwise I'd closely check all the logic in between the event generation and the test to make sure that there's no '=' where there should be a '==' and so forth.

You may want to fire up the debugger and try to get to the core of the problem.

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.
MylesEvans
MylesEvans

I'm just not figuring this out

BeerNutts
BeerNutts
Don't test for Key Up (ie Key Release), nor set bools for direction; Rather, set all velocities to 0 before testing for key down, then, when a Key is pressed (let's say Right is pressed), assign the X velocity there.

Like this (pseudoCode):


void Player::Update()
{
  XVelocity = 0;
  YVelocity = 0;

  if (KeyPressed(KEY_UP) {
    YVelocity = -1;
  }
  if (KeyPressed(KEY_DOWN) {
    YVelocity = 1;
  }
  if (KeyPressed(KEY_LEFT) {
    XVelocity = -1;
  }
  if (KeyPressed(KEY_RIGHT) {
    XVelocity = 1;
  }

  // Move the player based on the velocity
  XLocation += XVelocity;
  YLocation += YVelocity;  

  ...
My Gamedev Journal: 2D Game Making, the Easy Way

---(Old Blog, still has good info): 2dGameMaking
-----
"No one ever posts on that message board; it's too crowded." - Yoga Berra (sorta)
Khatharr
Khatharr
The problem is with the key event messages that he's getting from SDL. He doesn't have a 'pressed' function (unless there's one in SDL that he's not using) - he's trying to create one based on key-up/key-down messages.
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.
BeerNutts
BeerNutts
The problem is with the key event messages that he's getting from SDL. He doesn't have a 'pressed' function (unless there's one in SDL that he's not using) - he's trying to create one based on key-up/key-down messages.

There is. He should look at SDL_GetKeyState()

My Gamedev Journal: 2D Game Making, the Easy Way

---(Old Blog, still has good info): 2dGameMaking
-----
"No one ever posts on that message board; it's too crowded." - Yoga Berra (sorta)
Khatharr
Khatharr
Aye, there we go.
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.
MylesEvans
MylesEvans

I tried that method. It was the first thing I tried


If I hold down the key the payer doesn't move. I have to repeatedly tap the key. 

void handleKeys( unsigned char key, int x, int y )
{
Uint8 *keystates = SDL_GetKeyState(NULL);

if( keystates[SDLK_w])
{
PlayerY += 10;
}
else if( keystates[SDLK_s])
{
PlayerY -= 10;
}
else if( keystates[SDLK_d])
{
PlayerX += 10;
}
else if( keystates[SDLK_a])
{
PlayerX -= 10;
}
}

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.