3
\$\begingroup\$

I'm using Unity / C# to make a variation on a 360-degree snake game, but I'm having trouble just getting the movement of the tail right (I have a similar problem as in this question: How To Approach 360 Degree Snake, but I think my game is structured a little differently). I'm running into the problem where the snake's tail does follow the head, but instead of getting longer, the tail game objects just stack on top of each other. They are spawning in the right spot (which is behind the head, at a distance based on the size of the tail) but moving to the stack. In my code, I've left in some stuff that is commented out, because that almost worked...but it created some strange problems as well. Anyway, here is my code for the "Move" function, and I'd greatly appreciate any help!

    // Save current position
    Vector3 pos = transform.position;
    pos -= transform.right;

    // Move head into direction of rotation
    transform.Rotate (0, 0, rotation);
    transform.Translate (Vector2.right * Time.deltaTime * moveSpeed);

    // Insert new element if the snake has eaten
    if (ate) {
        pos -= transform.right * tail.Count;

        // Load Prefab
        GameObject g = (GameObject)Instantiate (tailPrefab, pos, transform.rotation);

        // Keep track of it the tail list
        tail.Insert (0, g.transform);

        // Reset the ate bool
        ate = false;
    } 
    if (tail.Count == 1) {
        tail [0].position = pos;
        tail [0].rotation = transform.rotation;
    }
    // Is there a multiple tail
    else if (tail.Count > 1)
    {
        // Move last Tail to where the Head was
        tail.Last().position = pos;
        tail.Last().rotation = transform.rotation;

        // Add to front of list and remove from the back
        tail.Insert(0, tail.Last());
        tail.RemoveAt(tail.Count - 1);
        /*
        Vector3 unitShift = transform.right;
        for (int i = 1; i < tail.Count; i += 1) {
            tail[i].position = v - unitShift * i;
        }

        /*
        // I guess I need an array of positions?
        Vector3[] positions = new Vector3[tail.Count];
        for (int i = 0; i < tail.Count; i += 1) {
            positions[i] = tail[i].position;
        }

        // loop through tail elements and make them follow the head
        for (int i = 1; i < tail.Count; i += 1) {
            tail[i].position = positions[i];
            tail[i].rotation = transform.rotation;
        }
        /*
         */
    }
}
\$\endgroup\$
1
  • \$\begingroup\$ Take a look at your IF nestings ;) you're moving the tail regardless if the snake ate anything or not. \$\endgroup\$
    – Stephan
    Jul 10, 2015 at 15:50

0

Browse other questions tagged .