unity 制作贪吃蛇的代码
时间: 2023-11-06 15:31:08 浏览: 58
以下是一个简单的Unity贪吃蛇游戏的代码示例:
```
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Snake : MonoBehaviour {
// 蛇头
public GameObject headPrefab;
private GameObject head;
// 蛇身
public GameObject bodyPrefab;
private List<GameObject> bodyParts = new List<GameObject>();
// 移动速度
public float speed = 0.1f;
// 移动方向
private Vector3 direction = Vector3.right;
// 下一个移动位置
private Vector3 nextPosition;
void Start () {
// 创建蛇头
head = Instantiate(headPrefab) as GameObject;
head.transform.position = Vector3.zero;
// 创建蛇身
AddBodyPart();
AddBodyPart();
}
void Update () {
// 获取输入方向
float h = Input.GetAxisRaw("Horizontal");
float v = Input.GetAxisRaw("Vertical");
if (h != 0) {
direction = (h > 0) ? Vector3.right : Vector3.left;
} else if (v != 0) {
direction = (v > 0) ? Vector3.up : Vector3.down;
}
// 计算下一个移动位置
nextPosition = head.transform.position + direction;
// 移动蛇头
head.transform.position = nextPosition;
// 移动蛇身
for (int i = bodyParts.Count - 1; i > 0; i--) {
bodyParts[i].transform.position = bodyParts[i - 1].transform.position;
}
bodyParts[0].transform.position = head.transform.position;
}
// 添加一个蛇身部分
void AddBodyPart() {
GameObject body = Instantiate(bodyPrefab) as GameObject;
body.transform.position = new Vector3(0, -1, 0) - new Vector3(bodyParts.Count * 0.1f, 0, 0);
bodyParts.Add(body);
}
}
```
上面的代码创建了一个简单的贪吃蛇游戏,其中使用了Unity的基本功能,如Instantiate(创建游戏对象)和Input.GetAxisRaw(获取输入方向)。通过按下方向键来改变蛇的方向,并在Update方法中移动蛇头和蛇身。添加一个新的蛇身部分时,我们使用了Instantiate方法,并将其位置设置为当前蛇身部分的数量。希望这个代码示例能帮助你更好地了解如何在Unity中创建贪吃蛇游戏。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)