Sign in to follow this  
parinho7

Movement problem in snake game

Recommended Posts

parinho7    213
I am in the process of making a classic snake game but I have a problem with the movement.

If the snake goes up it normally won't react if you press down. But if it goes up and then I hit right(or left) and then quickly hit down the program isn't able to render it but apparently it recognizes the change of direction so the snake goes down. Same goes for every other direction.

What can I do to fix this?

Here is my code help me please. Thanks in advance!

[CODE]
void CSnake::Event(SDL_Event &event){
if (SDL_KEYDOWN)
switch (event.key.keysym.sym){
case SDLK_UP:
if (dir!=DOWN){
yVel = -20;
xVel = 0;
dir = UP;
}
break;
case SDLK_DOWN:
if (dir!=UP){
yVel = 20;
xVel = 0;
dir = DOWN;
}
break;
case SDLK_LEFT:
if (dir!=RIGHT){
xVel = -20;
yVel = 0;
dir=LEFT;
}
break;
case SDLK_RIGHT:
if (dir!=LEFT){
xVel = 20;
yVel = 0;
dir=RIGHT;
}
break;
}
}
void CSnake::movement(){
if (t_MoveTime <= (SDL_GetTicks()-t_SnakeStarted)){
SDL_Rect front;
iSnake = snake.begin();
front.x = (*iSnake).x + xVel;
front.y = (*iSnake).y + yVel;
snake.push_front(front);
snake.pop_back();
t_SnakeStarted = SDL_GetTicks();
}
}
[/CODE] Edited by parinho7

Share this post


Link to post
Share on other sites
deathwearer    367
Hey,

I think you must only change your snake current direction only when it has at least moved one square of the new direction (If your snake game is moving square by square).

Maybe have a currentDirection and lastDirection variable. You use the current direction to do your movement, and once at least one movement was made in the new direction you do lastDirection = currentDirection.

Then you allow changing the currentDirection only if currentDirection = lastDirection AND is either one of them is not equal to the direction you don't allow (For exemple, going from up to down).

OR

if your game is somewhat "TIck based" (like the original Snake) only allow one direction change per tick. There would be one draw by tick so you couldn't go from up to down without at least going left of right for a tick.

Share this post


Link to post
Share on other sites
parinho7    213
[quote name='deathwearer' timestamp='1355187221' post='5009258']
if your game is somewhat "TIck based" (like the original Snake) only allow one direction change per tick. There would be one draw by tick so you couldn't go from up to down without at least going left of right for a tick.
[/quote]

YES! thank you, problem solved!!! Edited by parinho7

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