这个贪吃蛇借鉴了网上的一个算法,其他代码部分就是自己写的了。
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine.UI;
public class SnakeMove : MonoBehaviour
{
public GameObject scene;//绑定场景
public GameObject SSFood;//绑定食物
public GameObject gameObjecgtBody;//绑定身体
public float velocityTime = 0.1f;//执行延时时间
public Text Score;//UI分数
Vector3 direction = Vector3.up;//初始移动方向
List<Transform> Body = new List<Transform>();//存储身体的列表
private bool flag = false; //判断是否撞上去
private int score = 0;//计算分数
void Start()
{
//延时执行 并且每个velocityTime在执行一次
InvokeRepeating("Move", 5f, velocityTime);//检查是否吃了食物
InvokeRepeating("ShowFood", 1, 4);//生成食物
}
void Update()
{
Score.text = score.ToString();
//按下WASD或者光标键移动 且不能向反方向移动
if ((Input.GetKey(KeyCode.W