2017-01-03 15 views
0

私は蛇のゲームに取り組んでいます。3秒ごとに発生するFOOD PREFABを追加しましたが、それ自体を破壊せず、衝突したとき。 私はHEAD用のこのコードを持っています、これは私の問題がある場所だと思います。Unity3Dのスネークゲームで食べ物に衝突したときにテールが追加されない

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 
     } 
    } 
} 
+2

プレハブに剛体を追加しましたか? –

+0

私は食品にrigidbody2dを追加しました。しかし、それが表示され、エラーが発生しました "SNAKEの変数TAIL_PREFABが割り当てられていません" –

+2

これはあなたのate varがtrueに設定されているので、素晴らしいことです。Unity InspectorからTAIL_PREFABを追加して、インスペクタのフィールド –

答えて

1

rigidbody2dを食品に追加すると、その作業を行う必要があります。

はよりhere

ハッピーコーディングを参照してください!

+0

ありがとうございました! :) –

関連する問題