一、实现效果
功能描述:
- 点击游戏手柄,贪吃蛇丝滑跟随
二、核心实现
1.在canvas面板上生成预制体
ps:之前没有在面板上做过项目,按以前的思路做预制体,发现面板上根本就没有出现预制体,研究后确实发现预制体得放在canvas里
代码实现:
GameObject canv = GameObject.Find(“Canvas”); //找到面板
GameObject newbodynext = Instantiate(body); //生成预制体
newbodynext.transform.SetParent(canv.transform, false);//再将它设为canvas的子物体
2.预制体跟随
ps:和之前一样的用到数组
这个有点分散,直接上代码(此代码用到上一章的物体移动方向的参数变量,即 rotation/thlta )
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Plane : MonoBehaviour
{
float timer = 0f; //设置加数
float interval = 0.2f; //循环一次的时间
float speed = 1.5f; //加的速度
public GameObject FoodPrefab;//食物预制体
public GameObject body;//身体预设体
List<GameObject> snakeBody = new List<GameObject>();//一定记住设对象数组的格式
void Start()
{
GameObject canv = GameObject.Find("Canvas");
for (int i = 0; i < 3; ++i)
{
Vector3 SnakeHeadPos = transform.position;
SnakeHeadPos.z = 0;
// Debug.Log("SnakeHeadPos:"+SnakeHeadPos);
GameObject newbodynext = Instantiate<GameObject>(body,
SnakeHeadPos - (i + 1) * new Vector3(0, 40f, 0f),/*40f是因为蛇头中心点与蛇身中心点的距离为40f*/ Quaternion.identity);
// Debug.Log("蛇身:"+newbodynext.transform.position);
newbodynext.transform.SetParent(canv.transform, false);//再将它设为canvas的子物体
snakeBody.Add(newbodynext);
}
}
void Update()
{
timer += speed * Time.deltaTime;
if (timer > interval)
{
timer = 0;
Vector3 tmpPosition = transform.position; //记录头部变化前的位置
List<Vector3> tmpList = new List<Vector3>(); //记录身体变化前的位置
for (int i = 0; i < snakeBody.Count; ++i)
{
tmpList.Add(snakeBody[i].transform.position);
}
transform.Translate(0, 0.5f, 0);//定时移动一定的距离(蛇头中心点到蛇身中心点的距离)
snakeBody[0].transform.position = tmpPosition;//将0移到头部之前的位置
for (int i = 1; i < snakeBody.Count; ++i)//依次前移身体的位置
{
snakeBody[i].transform.position = tmpList[i - 1];
}
}
//从中心圆获取Rotation的z值
float thlta_z = GameObject.Find("中心圆").GetComponent<CenterCircle>().thlta;
//Debug.Log("转角:"+thlta_z);
transform.rotation = Quaternion.Euler(0, 0, thlta_z);
}
}