Snake tail game

I am working on a 2D Snake Game in Unity. This is the head of the Snake:

head of snake

And this is the extension of the tail of the snake. It is added every time I eat something:

Extension of the tail of the snake

I made the snake's head move, but my question is: how do I move the extensions? I tried adding these extensions as children to the head, but when I turn my head, it rotates all the extensions at the same time, but I want to rotate one extension at a time, like a chain. I am using C # Script

   if (position == 1 || position == 3) {
                if (Input.GetKey (KeyCode.UpArrow)) {
                    position = 2;
                    rotation=90;
                    transform.rotation=Quaternion.Euler(0,0,rotation);

                } 

else if (Input.GetKey (KeyCode.DownArrow)) {
                position = 4;
                rotation=270;
                transform.rotation=Quaternion.Euler (0,0,rotation);
            }
        } else if (position == 2 || position == 4) {
            if(Input.GetKey(KeyCode.RightArrow)){
                position=1;
                rotation=0;
                transform.rotation=Quaternion.Euler (0,0,rotation);
            }
            else if(Input.GetKey(KeyCode.LeftArrow)){
                position=3;
                rotation=180;
                transform.rotation=Quaternion.Euler (0,0,rotation);
            }
        }
        if (position == 1)
            transform.Translate (Vector3.right * movementSpeed * Time.deltaTime,Space.World);
        else if (position == 2)
            transform.Translate (Vector3.up* movementSpeed * Time.deltaTime,Space.World);
        else if(position==3)
            transform.Translate(Vector3.left*movementSpeed*Time.deltaTime,Space.World);
        else if(position==4)
            transform.Translate (Vector3.down*movementSpeed*Time.deltaTime,Space.World);
        int i;
        for (i=1; i<extensions.Count; i++) {
            extensions[i].transform.position=extensions[i-1].transform.position;
            extensions[i].transform.rotation=extensions[i-1].transform.rotation;
        }
+4
source share
3 answers

, . 0 () 1 , 2 . . , , . , .

, .

, , . ( )

0

If you put each of the sections (including the head) in List, you can take each section in Update ()(or where you call your movement function) and move it to the position and rotation of the section immediately preceding it in the list. Thus, all you need to control the movement directly is the head; The following sections will navigate with exactly the same path.

0
source

Source: https://habr.com/ru/post/1608196/


All Articles