Jump to content

  • Log In with Google      Sign In   
  • Create Account


Moving a player while holding down a key.


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
21 replies to this topic

#1 GDsnakes   Members   -  Reputation: 145

Like
0Likes
Like

Posted 26 December 2012 - 05:55 PM

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.



Sponsor:

#2 Kaptein   Prime Members   -  Reputation: 2020

Like
0Likes
Like

Posted 26 December 2012 - 07:00 PM

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

#3 DpakoH   Members   -  Reputation: 950

Like
0Likes
Like

Posted 27 December 2012 - 02:02 AM

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



#4 GDsnakes   Members   -  Reputation: 145

Like
0Likes
Like

Posted 27 December 2012 - 01:02 PM

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.



#5 Khatharr   Crossbones+   -  Reputation: 2956

Like
0Likes
Like

Posted 27 December 2012 - 02:25 PM

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.

#6 GDsnakes   Members   -  Reputation: 145

Like
0Likes
Like

Posted 28 December 2012 - 10:07 PM

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.  
  6. //While there are events to handle
  7. while( SDL_PollEvent( &event ) )
  8. {
  9. if( event.type == SDL_QUIT )
  10. {
  11. quit = true;
  12. }
  13. else if( event.type == SDL_KEYDOWN )
  14. {
  15. //Handle keypress with current mouse position
  16. int x = 0, y = 0;
  17. SDL_GetMouseState( &x, &y );
  18. handleKeys( event.key.keysym.unicode, x, y );
  19. }
  20. }

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.

 



#7 AdrianC   Members   -  Reputation: 602

Like
0Likes
Like

Posted 28 December 2012 - 10:35 PM

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
}


#8 superman3275   Crossbones+   -  Reputation: 2011

Like
0Likes
Like

Posted 29 December 2012 - 01:17 AM

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 ph34r.png!

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 smile.png!


#9 GDsnakes   Members   -  Reputation: 145

Like
0Likes
Like

Posted 29 December 2012 - 10:31 AM

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


#10 Khatharr   Crossbones+   -  Reputation: 2956

Like
0Likes
Like

Posted 29 December 2012 - 10:47 AM

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?


Edited by Khatharr, 29 December 2012 - 11:06 AM.

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.

#11 GDsnakes   Members   -  Reputation: 145

Like
0Likes
Like

Posted 29 December 2012 - 01:23 PM

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.



#12 Khatharr   Crossbones+   -  Reputation: 2956

Like
0Likes
Like

Posted 29 December 2012 - 03:07 PM

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.

#13 GDsnakes   Members   -  Reputation: 145

Like
0Likes
Like

Posted 29 December 2012 - 04:43 PM

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.



#14 Khatharr   Crossbones+   -  Reputation: 2956

Like
0Likes
Like

Posted 29 December 2012 - 09:02 PM

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.

#15 GDsnakes   Members   -  Reputation: 145

Like
0Likes
Like

Posted 01 January 2013 - 11:36 PM

I'm just not figuring this out



#16 BeerNutts   Crossbones+   -  Reputation: 2778

Like
0Likes
Like

Posted 02 January 2013 - 02:11 PM

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)

#17 Khatharr   Crossbones+   -  Reputation: 2956

Like
0Likes
Like

Posted 02 January 2013 - 03:48 PM

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.

#18 BeerNutts   Crossbones+   -  Reputation: 2778

Like
0Likes
Like

Posted 02 January 2013 - 04:20 PM

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)

#19 Khatharr   Crossbones+   -  Reputation: 2956

Like
0Likes
Like

Posted 02 January 2013 - 06:32 PM

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.

#20 GDsnakes   Members   -  Reputation: 145

Like
0Likes
Like

Posted 03 January 2013 - 12:20 PM

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


Edited by GDsnakes, 03 January 2013 - 12:25 PM.





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