記錄一下前段時間寫到的一個3d貪喫蛇的移動代碼。
鏈接:https://pan.baidu.com/s/1A20rPyKoWf5RsqL6ehBQhA
提取碼:vs6f
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameManager : MonoBehaviour
{
List<Transform> bodyList = new List<Transform>();//身體位置的列表
private float speed = 2f;//移動速度
public GameObject bodyObj;//用來生成的身體對象
List<Transform> bodyCreatePostion = new List<Transform>();//身體部分的transfrom 列表
private float TransOffset=1f;//位置間隔
private List<Vector2> mapAddress=new List<Vector2>();//前進目標在地圖上的位置,
public Transform firstBody;//第一個身體部件的transfrom
const int row = 100;//地圖寬
const int col = 100;//地圖高
int step=1;//步伐
int x=0, z=0;//記錄x和z軸的移動量
// Start is called before the first frame update
public Vector3[,] map = new Vector3[row, col];//地圖
// Start is called before the first frame update
void Start()
{
for (int i = 0; i < row; i++)//生成地圖
{
for (int j = 0; j < col; j++)
{
map[i, j] = new Vector3(i, 1.5f, j);
}
}
transform.position =map[0,0];將當前位置設爲原點
mapAddress.Add(new Vector2(1,0));//增加第一個目標
bodyList.Add(transform);//刷新第一個頭和一個身體的transform
bodyList.Add(firstBody);
mapAddress.Add(new Vector2(0,0));
}
// Update is called once per frame
void Update()
{
for (int i = 0; i < row - 1; i++)
{
for (int j = 0; j < col - 1; j++)//繪製地圖格子
{
Debug.DrawLine(map[i, j], map[i + 1, j], Color.red);
Debug.DrawLine(map[i, j], map[i, j + 1], Color.red);
}
}
if (Input.anyKeyDown)//有任何鍵按下
{
if (Input.GetKeyDown(KeyCode.W) && z != -step)//上
{
z = step;
x = 0;
}
if (Input.GetKeyDown(KeyCode.S) && z != step)//下
{
z = -step;
x = 0;
}
if (Input.GetKeyDown(KeyCode.A) && x != step)//左
{
x = -step;
z = 0;
}
if (Input.GetKeyDown(KeyCode.D) && x != -step)//右
{
x = step;
z = 0;
}
}
Move();
}
private void Move()//移動
{
if (Vector3.Distance(bodyList[0].position, map[(int)mapAddress[0].x + x, (int)mapAddress[0].y + z]) < 0.7f)//當前座標和目標位置的距離小於0.5f
{
for (int i = mapAddress.Count - 1; i > 0; i--)//刷新後一個的目標爲前一個的目標
{
mapAddress[i] = mapAddress[i-1];
}
mapAddress[0] = new Vector2(mapAddress[0].x + x, mapAddress[0].y + z);//刷新第一個目標的位置
}
else
{
for (int i = bodyList.Count - 1; i > 0; i--)//移動
{
bodyList[i].position = Vector3.MoveTowards(bodyList[i].position,
map[(int)mapAddress[i - 1].x, (int)mapAddress[i - 1].y], Time.deltaTime * speed);
}
bodyList[0].position = Vector3.MoveTowards(transform.position,
map[(int)mapAddress[0].x + x, (int)mapAddress[0].y + z], Time.deltaTime * speed);
}
}
private void OnCollisionEnter(Collision collision)//碰撞到了食物就增加身體長度
{
if (collision.collider.tag == "Food")
{
Destroy(collision.collider.gameObject);
GameObject tmpGameObject=new GameObject();
Vector2 tmpVec = new Vector2();
tmpGameObject = Instantiate(bodyObj, map[(int)mapAddress[mapAddress.Count - 1].x+x, (int)mapAddress[mapAddress.Count - 1].y +z], Quaternion.identity);//生成body物體
tmpVec = new Vector2(mapAddress[mapAddress.Count - 1].x+x, mapAddress[mapAddress.Count - 1].y +z);
//增加身體的transform和目標向量
bodyList.Add(tmpGameObject.transform);
mapAddress.Add(tmpVec);
}
}
}