贪吃蛇方案

这里只给点思路。没有完整的做出效果来

创建头 Head(一个立方体)绑定senk.cs脚本

senk.cs代码

 1 using UnityEngine;
 2 using System.Collections;
 3 
 4 
 5 //蛇头移动代码
 6 public class senk : MonoBehaviour
 7 {
 8 
 9     float timeer;
10     float timeOff;
11 
12 
13     public BodyFolloyw next;
14 
15 
16     Vector3 originPositon; //蛇头移动前的位置
17 
18     public GameObject Prefab;
19 
20 
21     BodyFolloyw tail;
22 
23     // Use this for initialization
24     void Start()
25     {
26         timeer = 0;
27         timeOff = 1;
28     }
29 
30     // Update is called once per frame
31     void Update()
32     {
33         Move();
34         Turn();
35         AddTail();
36 
37 
38     }
39 
40     /// <summary>
41     /// 移动
42     /// </summary>
43     void Move()
44     {
45         timeer += Time.deltaTime;
46         if (timeer > timeOff)
47         {
48             originPositon = transform.position;
49             transform.Translate(Vector3.forward);
50             timeer = 0;
51 
52             if (next)
53             {
54                 next.Follow(originPositon);
55             }
56         }
57 
58     }
59 
60     /// <summary>
61     /// 拐弯
62     /// </summary>
63     void Turn()
64     {
65         if (Input.GetKeyDown(KeyCode.A))
66         {
67             transform.Rotate(Vector3.up * -90);
68         }
69         if (Input.GetKeyDown(KeyCode.D))
70         {
71             transform.Rotate(Vector3.up * 90);
72         }
73     }
74     BodyFolloyw body;
75     void AddTail()
76     {
77         if (Input.GetMouseButtonDown(0))
78         {
79             body = ((GameObject)Instantiate(Prefab, Vector3.one * 999, Quaternion.identity)).GetComponent<BodyFolloyw>();
80 
81             if (!next) //第一个身体产生的时候
82             {
83                 next = body;
84                 tail = next;
85             }
86             else
87             {
88                 tail.next = body;
89                 tail = tail.next;
90             }
91         }
92     }
93 }

创建一个预设体body1,赋值给senk.cs脚步中的public GameObject Prefab;作为蛇的身体

然后body1预设体绑定脚本BodyFolloyw.cs

BodyFolloyw.cs代码

 1 using UnityEngine;
 2 using System.Collections;
 3 
 4 
 5 //蛇的其他部位移动
 6 public class BodyFolloyw : MonoBehaviour
 7 {
 8 
 9     // Use this for initialization
10     void Start()
11     {
12 
13     }
14 
15     // Update is called once per frame
16     void Update()
17     {
18 
19     }
20 
21     public BodyFolloyw next;
22 
23     Vector3 originposition;
24 
25     public void Follow(Vector3 position)
26     {
27         originposition = transform.position;
28 
29         transform.position = position;
30 
31         if (next)
32         {
33             next.Follow(originposition);
34         }
35     }
36 }

好了。这样就实现了。鼠标左键单击。就会增加一个身体。基本思路这样。有时间在完成一个成品吧。现在太累了。唉!!

原文地址:https://www.cnblogs.com/nsky/p/4611579.html