I have my snake game and im facing a weird bug, if im going to the right and quickly press up and left i die, is there a way to solve this?
I need help with my snake game
Without reading through your code, I'm guessing that what's happening is that your snake is turning upwards and then--before it has cleared its body-width--turning left, thus causing it to collide with itself.
If so, then there are a few potential approaches to this, I think.
One might be to consider it a feature, not a bug: timing one's inputs is part of the challenge.
However, the above may not prove fun, so another approach might be to store inputs until the snake has moved one body-width in its current direction. Only once this point has been passed would the input would be enacted. This should then result in the snake only turning when it has cleared its own width, preventing it from reversing into itself.
During the wait to use an input, I might suggest that subsequent inputs replace whatever input is already held--that way the player can correct themselves, and furthermore doesn't end up with a huge number of buffered actions.
MWAHAHAHAHAHAHA!!!
My Twitter Account: @EbornIan
I see you tried to fix it here:
void move(sf::Vector2f &dir,sf::Vector2f &last_direction){
update_pos();
makethatshitnotkillitself(dir,last_direction);
snek_head.move(dir.x,dir.y);
wrap();
self_collision();
}
- selfcollision returns 0 or 1, so calling this method does nothing.
- Do not call update_pos first in this method because it appears that you have not made any movements, so why update before moving the head? So first move the head, then check for the wrapping, then update the position.
- The move method should not take both the current and previous direction. It should only take the direction you wish to move as a parameter (to keep things simple).
- Get rid of "and !(curr_direction == direction_.left)". The result of a keypress should only set the direction you WISH to travel in.
if (Time1 <= move_t and move_b == true and game_over == 0){
if(apple.check_collision(snake)){snake.add_body();score.setString("score: "+std::to_string(apple.score));}
snake.move(curr_direction,last_direction);
cout << last_direction.x <<"::"<< last_direction.y << endl;
//cout << snake.snek_head.getPosition().x <<"::"<<snake.snek_head.getPosition().y << endl;
move_b = false;
}
5. Most importantly, BEFORE you call the move method here, make sure you can move in that direction. Like: if(desired_direction != opposite_of_last_direction). ONLY if this condition passes do you change the last_direction.
Lastly, funny variable names.