SFML Snake Body movement.

Hello, i'm making a snake game and I can't figure out how to get my snake's body to move accordingly with the head. I've tried a bounch of different ways of setting the position of the parts but so far all the results have been failiures.
I got close to a solution once but then the problem came that I couldn't get the body parts to turn when the head makes a turn.

Here is how the move function looks like right now, it is currently not working. With
this function the parts are all inside the head.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  void Snake::move(float x, float y, float dt)
{
	this->playerSprite.move(x*dt, y*dt);
	newX = lastX;
	newY = lastY;
	for (int i = 0; i < nrOfParts; i++)
	{
		if (bodyParts[0].getPosition() != bodyParts[nrOfParts].getPosition())
		{
			lastX = bodyParts[0].getPosition().x;
			lastY = bodyParts[0].getPosition().y;
			bodyParts[i].setPos(newX, newY);
			newX = lastX;
			newY = lastY;
		}
	}
	
}


And here is how it looks like when it's almost working, only problem is that the parts
aren't turning when the head turns- they just follow after and change direction all together.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void Snake::move(float x, float y, float dt)
{
	lastX = playerSprite.getPosition().x - x / 2;
	lastY = playerSprite.getPosition().y - y / 2;
	this->playerSprite.move(x*dt, y*dt);
	newX = lastX;
	newY = lastY;
	for (int i = 0; i < nrOfParts; i++)
	{
		lastX = bodyParts[i].getPosition().x - x / 2;
		lastY = bodyParts[i].getPosition().y - y / 2;
		bodyParts[i].setPos(newX, newY);
		newX = lastX;
		newY = lastY;
	}
	
}
Last edited on
Topic archived. No new replies allowed.