• 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
munchor

[SDL] Moving right and left

3 posts in this topic

[CODE]

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);
}
[/CODE]

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
0

Share this post


Link to post
Share on other sites
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 ([i]Keypress -> Move 5 pixels. Keypress -> Move 5 pixels[/i]). What you want is ([i]While the keypress is down, keep moving five pixels each frame[/i]*).

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 "[i]while (running)[/i]" loop, based off of the input change the internal state of the game ([i]PlayerMovingLeft = true, PlayerMovingRight = false[/i]), and regardless of whether there is input or not, every frame react to the internal state of the game ([i] if(PlayerMovingLeft) {...move the player five pixels...}[/i] ).

*[size=2]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.[/size]

So that's the first issue, and your code should now look like this:
[CODE]
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);
}
[/CODE]


[left]The second issue, is that you aren't checking the return value of SDL_PollEvent(). It returns [b]true[/b] if there is input, otherwise it returns [b]false[/b] and you're not supposed to use the [color=#000088][size=2]'[/size][/color]event' variable for anything.[/left]

[left]So your entire input should be wrapped in an if(...) statement, like this:[/left]
[left][code] 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)
{
...
}
}
[/code][/left]

The third issue is this: You might get more than one input event each frame! So the "[i]if( SDL_PollEvent(&event) )[/i]" should actually be a "[i][b]while[/b]( SDL_PollEvent(&event) )[/i]", 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:
[code]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);
}[/code]

This should completely fix your problem - these are common mistakes, ones which have burned me a couple of times when starting out. [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img]

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
0

Share this post


Link to post
Share on other sites
You can also use [url="http://sdl.beuc.net/sdl.wiki/SDL_GetKeyState"]SDL_GetKeyState[/url]() to read keypresses, like this:

[CODE]
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--;
[/CODE]

...and thus get rid of the '[i]playerMovingLeft[/i]' and '[i]playerMovingRight[/i]' 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
0

Share this post


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