该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum Direction{
Right,
Left,
Front,
Back
};
public class Snake : MonoBehaviour {
private LinkedList snakeList = null;
public GameObject foodGo;
float timer=0;
float tempX=1;
float tempZ=0;
Direction dir=Direction.Right;
bool isFood=false;
private Transform foodtrans;
// Use this for initialization
void Start () {
CreatSnakeList ();
}
// Update is called once per frame
void Update () {
SnakeMove ();
CreatFood ();
SnakeEatFood ();
}
//生成食物
void CreatFood(){
if (isFood == true) {
return;
} else {
float foodx = Random.Range (-15f,15f);
float foodz = Random.Range (-15f,15f);
float foody = 1f;
GameObject food= Instantiate (foodGo,new Vector3(foodx,foody,foodz),foodGo.transform.rotation);
foodtrans = food.transform;
isFood=true;
}
}
//吃掉食物
void SnakeEatFood()
{
LinkedListNode head = snakeList.First;
float distance = Vector3.Distance (head.Value.position,foodtrans.position);
print (distance);
if (distance < 1) {
Destroy (foodtrans.gameObject);
snakeList.AddLast(foodtrans);
foodtrans.SetParent(transform);
isFood = false;
}
}
//移动
//控制头的移动,来控制尾巴的位置
void SnakeMove()
{
if (Input.GetKeyDown (KeyCode.A)&&dir!=Direction.Right) {
tempX = 1;
tempZ = 0;
dir = Direction.Left;
} else if (Input.GetKeyDown (KeyCode.D)&&dir!=Direction.Left) {
tempX = -1;
tempZ = 0;
dir = Direction.Right;
}else if (Input.GetKeyDown (KeyCode.W)&&dir!=Direction.Front) {
tempX = 0;
tempZ = -1;
dir = Direction.Back;
}else if (Input.GetKeyDown (KeyCode.S)&&dir!=Direction.Back) {
tempX = 0;
tempZ = 1;
dir = Direction.Front;
}
timer += Time.deltaTime;
if (timer >= 0.5f) {
timer = 0;
LinkedListNode head = snakeList.First;
Vector3 savePos = head.Value.localPosition;
Vector3 tempPos = head.Value.localPosition;
tempPos.x += tempX;
tempPos.z += tempZ;
head.Value.localPosition = tempPos;
while (head.Next != null) {
Vector3 sPos = head.Next.Value.localPosition;
head.Next.Value.localPosition = savePos;
head = head.Next;
savePos = sPos;
}
}
}
//创建蛇的链表
void CreatSnakeList()
{
snakeList = new LinkedList ();
Transform[] trans = this.GetComponentsInChildren();
foreach (Transform t in trans) {
if (t.gameObject.name == "Snake")
continue;
snakeList.AddLast (t);
}
}
}