顺畅换道
Coddy Unity 游戏:天空赛道 课程的第 2 课,共 21 课。
跑者会在一帧内从一条赛道跳到另一条赛道。这样确实能运行,但看起来像是在瞬移。切换赛道应该花一点时间,这样你才能看清它的移动过程。
Mathf.MoveTowards(current, target, maxStep) 会让一个数字朝目标移动,最多移动 maxStep,绝不会越过目标。每帧调用一次,并将速度乘以 Time.deltaTime 作为步长,无论帧率是多少,它每秒都会按这个速度移动相应的单位数:
float x = Mathf.MoveTowards(transform.position.x, targetX, laneSpeed * Time.deltaTime);当 laneSpeed 为 16 时,切换一条相距 2.5 个单位的赛道大约需要 0.16 秒:速度很快,但你能看清移动过程。
挑战
简单让换道变得平滑,而不是跳过去。
- 在
laneWidth下方添加public float laneSpeed = 16f;。 - 将
float x = targetX;替换为上面的Mathf.MoveTowards这一行。
按下“开始”并切换车道:跑步者会平滑地移动过去。然后点击“检查”。
亲手试试
using UnityEngine;
public class Runner : MonoBehaviour
{
public float laneWidth = 2.5f;
public int lane;
private CharacterController controller;
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);
float targetX = lane * laneWidth;
float x = targetX;
Vector3 move = new Vector3(x - transform.position.x, 0f, 0f);
controller.Move(move);
}
}
Unity 游戏:天空赛道中的所有课
自己练习: Unity 在线编辑器