链表结构(贪吃蛇小游戏)

实现原理

为蛇的身体每一个节点添加脚本BodyFollow,使其能跟随父节点移动和设置它的子节点

 1 public class BodyFollow : MonoBehaviour {
 2 
 3     //下一个节点.
 4     public BodyFollow next;
 5 
 6     //本节点当前位置.
 7     Vector3 originalPisition;
 8 
 9     //节点移动的方法.
10     public void Follow(Vector3 gotoPosition)
11     {
12         //移动前记录下当前位置.
13         originalPisition = this.transform.position;
14 
15         //将节点移动至上一个节点的位置.
16         this.transform.position = gotoPosition;
17 
18         //如果存在下一个节点,则递归调用其移动方法.
19         if(next)
20         {
21             next.Follow(originalPisition);
22         }
23     }
24 
25 }

游戏实现过程

1、首先添加一个Cube作为小蛇的头部,再添加一个Cube作为小蛇的身体,拖为预设体,改变它的颜色和大小,使其能跟头部区分开来,然后添加一个Sphere并拖为预设体作为食物

2、在小蛇的身体上添加之前写好的BodyFollow脚本

3、给蛇的头部添加SnakeMove脚本

 1 public class SnakeMove1 : MonoBehaviour {
 2 
 3     //获取身体的预设体.
 4     public GameObject bodyPrefab;
 5 
 6     //小蛇的移动速度.
 7     public float moveSpeed;
 8 
 9     //记时器.
10     private float timer = 0;
11 
12     //当前位置.
13     private Vector3 originalPosition;
14 
15     //下一个节点.
16     BodyFollow next;
17 
18     //最后一个节点.
19     BodyFollow tail;
20     
21     void Start () 
22     {
23         AddBody();
24     }
25     
26     
27     void Update () {
28 
29         MoveController ();
30     }
31     
32     void MoveController()
33     {
34         //移动方法.
35         timer += Time.deltaTime;
36         if(timer > 1 / moveSpeed)
37         {
38             originalPosition = transform.position;
39             this.transform.Translate(Vector3.forward * 0.8f);
40             if(next)
41             {
42                 next.Follow(originalPosition);
43             }
44             timer -= 1 / moveSpeed;
45         }
46 
47         //方向控制.
48         if(Input.GetKeyDown(KeyCode.D) || Input.GetKeyDown(KeyCode.RightArrow))
49         {
50             this.transform.Rotate(Vector3.up * 90);
51         }
52         if(Input.GetKeyDown(KeyCode.A) || Input.GetKeyDown(KeyCode.LeftArrow))
53         {
54             this.transform.Rotate(Vector3.down * 90);
55         }
56 
57 
58     }
59 
60     //添加身体.
61     public void AddBody()
62     {
63         BodyFollow body = ((GameObject)Instantiate(bodyPrefab, Vector3.one * 9999, Quaternion.identity)).GetComponent<BodyFollow>();
64 
65         //如果不存在下一个节点,下一个节点就是新生成的那个body,尾部也是新生成的body.
66         if(!next)
67         {
68             next = body;
69             tail = next;
70         }
71 
72         //如果存在,把新生成的body设为下一个几点,尾部就是新生成的body.
73         else
74         {
75             tail.next = body;
76             tail = body;
77         }
78     }
79 
80 }

剩下吃食物增加身体的方法比较简单,这里就不写了, 简单的链表结构,如果有写得不好的地方还望大家多多提意见哈~

下面是比较完善的Demo,按任意键开始游戏,使用A、D或者←、→控制小蛇的转向

网页版预览

PC版下载

原文地址:https://www.cnblogs.com/zhenlong/p/4858744.html