Emerging Gap when moving my "Snake"

Hi there!

I am new to Unity but I am not as this new to C# - still I am a beginner.

So I am developing a snake game and I made a SpecialFood, which creates 5 new tails, when it is eaten. The 5 tails are added correctly, but after 6"Tails" has moved on - a gap is emerging (see Pic 1).

I can’t explain to myself why this is happening - but I think there is a problem with the list (I “storage” the tails in a List called “tail”).

So this is the code snippet for adding 5 tails:

//SpecialFood -> Add 5 Tails
for (int i = 0; i <= 4; i++ )
{

    //Instantiate a TailPrefab
    GameObject g = (GameObject)Instantiate(tailPrefab,
                                           v,
                                           Quaternion.identity);

    //Add it to the list         
    tail.Add(g.transform);
}

And this is the code for moving the tails:

// Move last Tail Element to where the Head was
tail.Last().position = v;

// Add to front of list, remove from the back
tail.Insert(0, tail.Last());
tail.RemoveAt(tail.Count-1);

If any more stuff is needed to help me solving this problem, please tell me.

Edit:

Vector2 v = transform.position;

Just if you are wondering, what “v” is.

Greetings

Okay, this approach was interesting to analyze. I think you don’t move the snake when you encounter the “superfood”:

![1]

It seems v is your current/head position. Then you spawn 3 segments there. Then you move those new segments first/next (since they are last in list). This results in a gap, because you never placed an “older” segment on v in a sequential order.

I guess you could move the snake, and instead spawn the new segments on at its tail old location.

Personally, I would keep a segmentToAdd counter. Each frame, when moving the snake, I would check if (segmentToAdd > 0) and spawn a segment instead (inserting at 0).