先建造一个场景 加入背景 灯光和蛇头 在四周建立Empty添加Boxcollider作为边界
之后将食物和蛇身做成预制件

制作游戏结束场景,添加一个text文本改为“贪吃蛇游戏,点击鼠标左键继续”

建立脚本添加在文字上
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class SnakeUI : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(Input.GetMouseButtonDown(0))
{
SceneManager.LoadScene(1);
}
}
}
给食物添加脚本使其随机在地图上生成
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FoodCreat : MonoBehaviour {
public GameObject s_food;
public int x_limit = 30;
public int y_limit = 16;
void Food()
{
int x = Random.Range(-x_limit, x_limit);
int y = Random.Range(-y_limit, y_limit);
Instantiate(s_food, new Vector2(x, y), Quaternion.identity);
}
// Use this for initialization
void Start () {
InvokeRepeating("Food",2,3f);
}
// Update is called once per frame
void Update () {
}
}
蛇头的脚本,包括身体的移动,碰撞检测
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using UnityEngine.SceneManagement;
public class SnakeMove : MonoBehaviour
{
List<Transform> body = new List<Transform>();
Vector2 direction = Vector2.up;
public GameObject snakeBody;
private bool flag;
float speed = 0.3f;
void Move()
{
Vector2 position = transform.position;
if (flag)
{
GameObject bodypfb = (GameObject)Instantiate(snakeBody, position, Quaternion.identity);
body.Insert(0, bodypfb.transform);
flag = false;
}
else if (body.Count > 0)
{
body.Last().position = position;
body.Insert(0, body.Last().transform);
body.RemoveAt(body.Count - 1);
}
this.transform.Translate(direction);
}
// Use this for initialization
void Start()
{
InvokeRepeating("Move", speed, speed);
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.W) || (Input.GetKeyDown(KeyCode.UpArrow)))
{
direction = Vector2.up;
}
else if (Input.GetKeyDown(KeyCode.S) || (Input.GetKeyDown(KeyCode.DownArrow)))
{
direction = Vector2.down;
}
else if (Input.GetKeyDown(KeyCode.A) || (Input.GetKeyDown(KeyCode.LeftArrow)))
{
direction = Vector2.left;
}
else if (Input.GetKeyDown(KeyCode.D) || (Input.GetKeyDown(KeyCode.RightArrow)))
{
direction = Vector2.right;
}
}
void OnTriggerEnter(Collider other)
{
if(other.gameObject.CompareTag("food"))
{
Destroy(other.gameObject);
flag = true;
}
else
{
SceneManager.LoadScene(0);
}
}
}


来源:oschina
链接:https://my.oschina.net/u/4462186/blog/3217460