Hello guys! I want to make snake game but i dont know how to make the body to follow the head so if anyone can explain me or give me example it will be good.
Thank you very much!
you could set the body positions from back to front and then move the head.
Now, I don't know how you store your data but I would have something like this:
struct Position {
int x, y;
Position& operator=(const Position& other) {
this->x = other.x;
this->y = other.y;
return *this;
}
};
// snake stores the position of each part of the snake
// snake[0] is the head, the rest are tails
std::vector<Position> snake;
enum Direction { UP, DOWN, LEFT, RIGHT };
void move(Direction dir)
{
for(int i = snake.size() - 1; i != 0; --i)
snake[i - 1] = snake[i];
switch(dir)
{
case UP: snake[0].y -= 1; break;
case DOWN: snake[0].y += 1; break;
case LEFT: snake[0].x -= 1; break;
case RIGHT: snake[0].x += 1; break;
}
}
Just in case you are unfamiliar with vector math, Vector2 in Gamer2015's code is just used to store a position. It has nothing to do with std::vector despite the name similarities.