James Dawson James Dawson - 4 months ago 30
ActionScript Question

Snake segments to follow a head in a snake game

I'm trying to write a snake game. It's pretty simple, there's an array of snake segments which are Sprites and they all have

values. On each game loop, I want to update the snake segments based on user input.

Note: the head of the snake is defined as
. The first element of the segments array is the head.

It seems logical to me to update the snakes head based on the users input and then have each snake segment after the head update to follow it. This is my code so far:

public function update()
// Update snake head
this.segments[0].x += 10;

for (var i:Number = 1; i < this.segments.length; i++)
// Set the segments position to be the same as the one before it
this.segments[i].x = this.segments[i - 1].x;
this.segments[i].y = this.segments[i - 1].y;

Hopefully you can see what you're doing here. I'm trying to set the segments x and y values to be the same as the one before it, so it will "follow".

Problem is, when I run this code, each snake segment piles on top of the same co-ordinate and it looks like one segment running around. They don't follow, they group up on top of each other.

For me the logic looks solid, so what gives?



Reverse your loop ( do last segment going to first ).

And do the head last.

Basically, segment i is grabbing i-1's location which has already updated.