在Unity3D的蛇游戏中碰撞食物时尾巴不会添加

时间:2017-01-03 13:30:49

标签: c# unity3d

我正在进行蛇形游戏,我添加了一个每隔3秒产生一次的食物预备,但它不会自行消灭并在碰撞时在头部添加尾巴。 我有HEAD的这个代码,我想这就是我的问题所在。

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

public class SNAKE : MonoBehaviour {

    // Did the snake eat something?
    bool ate = false;
    // Tail Prefab
    public GameObject TAIL_PREFAB;
    // Current Movement Direction
    // (by default it moves to the right)
    Vector2 dir = Vector2.right;
    // Keep Track of Tail
    List<Transform> tail = new List<Transform>();

    // Use this for initialization
    void Start () {
        // Move the Snake every 300ms
        InvokeRepeating("Move", 0.2f, 0.2f);    
    }

    // Update is called once per frame
    // Update is called once per Frame
    void Update() {
        // Move in a new Direction?
        if (Input.GetKey(KeyCode.RightArrow))
            dir = Vector2.right;
        else if (Input.GetKey(KeyCode.DownArrow))
            dir = -Vector2.up;    // '-up' means 'down'
        else if (Input.GetKey(KeyCode.LeftArrow))
            dir = -Vector2.right; // '-right' means 'left'
        else if (Input.GetKey(KeyCode.UpArrow))
            dir = Vector2.up;
    }



    void Move() {
        // Save current position (gap will be here)
        Vector2 v = transform.position;

        // Move head into new direction (now there is a gap)
        transform.Translate(dir);

        // Ate something? Then insert new Element into gap
        if (ate) {
            // Load Prefab into the world
            GameObject g =(GameObject)Instantiate(TAIL_PREFAB,v,Quaternion.identity);

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

            // Reset the flag
            ate = false;
        }
        // Do we have a Tail?
        else if (tail.Count > 0) {
            // 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);
        }
    }

    void OnTriggerEnter2D(Collider2D coll) {
        // Food?
        if (coll.name.StartsWith("FOOD")) {
            // Get longer in next Move call
            ate = true;

            // Remove the Food
            Destroy(coll.gameObject);
        }
        // Collided with Tail or Border
        else {
            // ToDo 'You lose' screen
        }
    }
}

1 个答案:

答案 0 :(得分:1)

在食物中添加一个刚体2d,应该可以完成这项工作。

查看更多here

快乐的编码!