回收道路
Coddy Unity 游戏:天空赛道 课程的第 7 课,共 21 课。
七块路段长 140 个单位。以每秒 10 个单位的速度运行,路段会在 14 秒后用完。每次需要时都新建一块路段,并销毁旧路段,也能实现这个效果,但还有一种更省成本的方法:把已经移到跑者身后的路段移到前方,再次使用。
当路段的中点越过 -chunkLength 后,它就完全位于身后了。一共有七块路段排成一列,因此把它向前移动七个路段长度,它就会正好位于最后一块之后:
if (chunk.position.z < -chunkLength)
{
chunk.position += Vector3.forward * chunkLength * chunks.Count;
}重复使用对象,而不是销毁并新建对象,这种做法叫对象池。七块路段就能组成一条没有尽头的道路。
挑战
简单每段道路经过跑步者身后后,都要重复使用。
- 在
Road.Update中,一段道路移动后,检查是否满足chunk.position.z < -chunkLength。 - 如果满足,就像上面那样,将它向前移动
chunkLength * chunks.Count。
按“运行”并等待 15 秒:道路不会耗尽。然后点击“检查”。
亲手试试
using UnityEngine;
public class Runner : MonoBehaviour
{
public float laneWidth = 2.5f;
public float laneSpeed = 16f;
public float jumpHeight = 1.6f;
public float gravity = -40f;
public float slideTime = 0.7f;
public int lane;
private CharacterController controller;
private float fallSpeed;
private float slide;
void Start()
{
controller = GetComponent<CharacterController>();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.A) || Input.GetKeyDown(KeyCode.LeftArrow)) lane = Mathf.Max(-1, lane - 1);
if (Input.GetKeyDown(KeyCode.D) || Input.GetKeyDown(KeyCode.RightArrow)) lane = Mathf.Min(1, lane + 1);
bool jump = Input.GetKeyDown(KeyCode.W) || Input.GetKeyDown(KeyCode.UpArrow) || Input.GetKeyDown(KeyCode.Space);
if (jump && controller.isGrounded)
{
fallSpeed = Mathf.Sqrt(jumpHeight * -2f * gravity);
StopSlide();
}
if ((Input.GetKeyDown(KeyCode.S) || Input.GetKeyDown(KeyCode.DownArrow)) && controller.isGrounded)
{
slide = slideTime;
Resize(0.5f);
}
if (slide > 0f)
{
slide -= Time.deltaTime;
if (slide <= 0f) StopSlide();
}
if (controller.isGrounded && fallSpeed < 0f) fallSpeed = -2f;
fallSpeed += gravity * Time.deltaTime;
float targetX = lane * laneWidth;
float x = Mathf.MoveTowards(transform.position.x, targetX, laneSpeed * Time.deltaTime);
Vector3 move = new Vector3(x - transform.position.x, fallSpeed * Time.deltaTime, 0f);
controller.Move(move);
}
void StopSlide()
{
if (transform.localScale.y < 1f) Resize(1f);
slide = 0f;
}
void Resize(float height)
{
controller.enabled = false;
transform.position += Vector3.up * (height - transform.localScale.y);
transform.localScale = new Vector3(1f, height, 1f);
controller.enabled = true;
}
}
Unity 游戏:天空赛道中的所有课
自己练习: Unity 在线编辑器