Menu
CoddyTech

提前观察

本课属于 Coddy Unity 学习旅程的“物理与游戏玩法”单元。第 49 课,共 71 课。

摄像机跟在移动的玩家正中间,会同时显示玩家走过的路和即将前往的方向。侧视摄像机可以稍微领先:放在玩家前方几个单位的位置,也就是玩家前进的一侧。

玩家转身时,领先方向也会反转,而领先位置立刻反转会让整个画面跳动。因此,把领先距离保存在一个字段中,并在每一帧用 Mathf.MoveTowards 将它逐渐移向新值。这个船只摄像机领先 2 个单位,并以每秒 3 个单位的速度移动:

float lead;
float heading = 1f;   // 1 表示向右航行,-1 表示向左航行

void LateUpdate()
{
    lead = Mathf.MoveTowards(lead, heading * 2f, 3f * Time.deltaTime);
    transform.position = new Vector3(boat.position.x + lead, transform.position.y, transform.position.z);
}

heading 表示船只上一次移动的方向:将它当前的 x 坐标与上一帧的 x 坐标进行比较。如果这一帧船只没有移动,就保持 heading 不变,这样船只静止时也会保持领先距离。

challenge icon

挑战

中等

让侧向摄像机显示跑者前进方向上更多的区域。

  1. 在 LateUpdate() 中,将跑者的 x 坐标与 lastX 比较:向右移动时将 direction 设为 1,向左移动时设为 -1,静止时保持不变。
  2. 逐渐调整 shift = Mathf.MoveTowards(shift, direction * ahead, shiftSpeed * Time.deltaTime);。
  3. 将摄像机的 x 坐标设为 player.position.x + shift,并保持 y 和 z 不变。

按“开始”,然后向两个方向跑。接着点击“检查”。

亲手试试

using UnityEngine;

public class LookAheadCamera : MonoBehaviour
{
    public Transform player;
    public float ahead = 3f;
    public float shiftSpeed = 4f;

    void LateUpdate()
    {
        // 沿玩家上次移动的方向,提前 ahead 个单位,并以 shiftSpeed 平滑移动。
        transform.position = new Vector3(player.position.x, transform.position.y, transform.position.z);
    }
}

物理与游戏玩法中的所有课

自己练习: Unity 在线编辑器