Unity 相机跟随玩家脚本

Ziv*_*ion 7 c# unity-game-engine

我对 Unity 还很陌生。我尝试创建一个镜头跟随演员的脚本(略有不同)。有没有办法改进代码?它工作得很好。但我想知道我是否以最好的方式做到了这一点。我想按照我写的那样做,所以如果你有任何提示。谢谢

也许更改UpdateFixedUpdate

public GameObject player;

// Start is called before the first frame update
void Start()
{
    player = GameObject.Find("Cube"); // The player
}

// Update is called once per frame
void Update()
{
    transform.position = new Vector3(player.transform.position.x, player.transform.position.y + 5, player.transform.position.z - 10);
}
Run Code Online (Sandbox Code Playgroud)

小智 17

让摄像机跟随玩家非常简单。

将此脚本添加到您的主相机。将播放器对象的引用拖到脚本中即可完成。

您可以根据您希望摄像机与玩家的距离来更改矢量 3 中的值。

using UnityEngine;

public class Follow_player : MonoBehaviour {

    public Transform player;

    // Update is called once per frame
    void Update () {
        transform.position = player.transform.position + new Vector3(0, 1, -5);
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 8

当玩家旋转时,持续跟随后面的玩家,无需家长控制,具有平滑功能。

知识点:

  • 显然,Quaternion * Vector3将围绕 Vector3 的原点旋转 Vector3 的点四元数的角度
  • Vector3 和 Quaternion 中的 Lerp 方法代表线性插值,其中每帧第一个参数与第二个参数的距离接近第三个参数的量。
using UnityEngine;

public class CameraFollow : MonoBehaviour

{
    public Transform target;
    public float smoothSpeed = 0.125f;
    public Vector3 locationOffset;
    public Vector3 rotationOffset;

    void FixedUpdate()
    {
        Vector3 desiredPosition = target.position + target.rotation * locationOffset;
        Vector3 smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);
        transform.position = smoothedPosition;

        Quaternion desiredrotation = target.rotation * Quaternion.Euler(rotationOffset);
        Quaternion smoothedrotation = Quaternion.Lerp(transform.rotation, desiredrotation, smoothSpeed);
        transform.rotation = smoothedrotation;
    }
}
Run Code Online (Sandbox Code Playgroud)