• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
MylesEvans

Moving a player while holding down a key.

21 posts in this topic

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.

0

Share this post


Link to post
Share on other sites
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.

0

Share this post


Link to post
Share on other sites

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.

 

0

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
Share on other sites

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

0

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
Share on other sites

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
0

Share this post


Link to post
Share on other sites
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.

0

Share this post


Link to post
Share on other sites

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.

0

Share this post


Link to post
Share on other sites
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.

0

Share this post


Link to post
Share on other sites

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.

0

Share this post


Link to post
Share on other sites
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;  

  ...
0

Share this post


Link to post
Share on other sites
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.
0

Share this post


Link to post
Share on other sites
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()

0

Share this post


Link to post
Share on other sites

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
0

Share this post


Link to post
Share on other sites

[quote name='GDsnakes' timestamp='1357237203' post='5017200']
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.
[/quote]

 

Yeah, but you have to call handleKeys() on EVERY LOOP, not just when an SDL Key Event is triggered.

 

If you are checking the key state every single loop, then you will always see the key is down, and it WILL always move.

0

Share this post


Link to post
Share on other sites

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.

 

 

Yeah, but you have to call handleKeys() on EVERY LOOP, not just when an SDL Key Event is triggered.

 

If you are checking the key state every single loop, then you will always see the key is down, and it WILL always move.

ahhh thank you very much. I just figured it out lol. You were right.

 

 

 

I love the Gamedev community! you guys are a big help.

0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0