用unity 写贪吃蛇
时间: 2023-05-23 11:06:32 浏览: 146
A: 以下是一个简单的Unity贪吃蛇游戏的示例:
1.创建一个Cube作为蛇身子。
2.创建一个Sphere作为食物。
3.编写一个脚本Snake.cs处理蛇的移动。
using UnityEngine;
using System.Collections;
public class Snake : MonoBehaviour
{
public float speed = 1;
private Vector3 dir;
private ArrayList bodyList = new ArrayList();
public GameObject bodyPrefab;
public int count = 0;
void Start ()
{
dir = new Vector3 (0, 0, speed);
StartCoroutine (Move ());
}
void Update ()
{
if (Input.GetKey (KeyCode.UpArrow) && dir != -Vector3.forward)
dir = Vector3.forward;
else if (Input.GetKey (KeyCode.DownArrow) && dir != Vector3.forward)
dir = -Vector3.forward;
else if (Input.GetKey (KeyCode.LeftArrow) && dir != Vector3.right)
dir = -Vector3.right;
else if (Input.GetKey (KeyCode.RightArrow) && dir != -Vector3.right)
dir = Vector3.right;
}
IEnumerator Move ()
{
while (true) {
transform.Translate (dir);
if (bodyList.Count > 0) {
Vector3 v = transform.position;
for (int i = 0; i < bodyList.Count; i++) {
GameObject go = (GameObject)Instantiate (bodyPrefab, v, Quaternion.identity);
bodyList [i] = go;
v = (bodyList [i] as GameObject).transform.position;
}
}
yield return new WaitForSeconds (0.2f);
}
}
void OnTriggerEnter (Collider other)
{
if (other.gameObject.CompareTag ("Food")) {
Destroy (other.gameObject);
count ++;
GameObject go = (GameObject)Instantiate (bodyPrefab, transform.position, Quaternion.identity);
bodyList.Insert (0, go);
}
}
}
4.编写一个脚本Food.cs在地图中随机生成食物。
using UnityEngine;
using System.Collections;
public class Food : MonoBehaviour
{
public GameObject foodPrefab;
public void CreateFood()
{
float x = Random.Range (-9, 9);
float z = Random.Range (-9, 9);
Instantiate (foodPrefab, new Vector3 (x, 0.5f, z), Quaternion.identity);
}
}
5.将Snake.cs和Food.cs挂载到场景中的游戏对象上。
6.在场景中创建一个空对象并添加Food.cs脚本,保证每隔几秒钟生成一个新的食物。
using UnityEngine;
using System.Collections;
public class GenerateFood : MonoBehaviour
{
public Food food;
void Start ()
{
food.CreateFood ();
StartCoroutine (Create ());
}
IEnumerator Create ()
{
while (true) {
yield return new WaitForSeconds (2f);
food.CreateFood ();
}
}
}
这样就可以实现一个简单的贪吃蛇游戏。
阅读全文