首页 > 解决方案 > 让相机跟随玩家对象在 3D 空间中的位置和旋转(Unity3d)

问题描述

我的目标是为我的太空战斗机概念验证游戏提供一个平滑的“跟随相机”。相机应在所有轴上匹配滚降目标对象。

为此,我从统一的 Answers 站点“窃取”并修改了这段代码,它对 X 和 Y(俯仰和偏航)工作得很好,但它拒绝滚动。

代码:

public float Distance;
public float Height;
public float RotationDamping;
public GameObject Target;

void LateUpdate()
{
    var wantedRotationAngleYaw = Target.transform.eulerAngles.y;
    var currentRotationAngleYaw = transform.eulerAngles.y;

    var wantedRotationAnglePitch = Target.transform.eulerAngles.x;
    var currentRotationAnglePitch = transform.eulerAngles.x;

    var wantedRotationAngleRoll = Target.transform.eulerAngles.z;
    var currentRotationAngleRoll = transform.eulerAngles.z;

    currentRotationAngleYaw = Mathf.LerpAngle(currentRotationAngleYaw, wantedRotationAngleYaw, RotationDamping * Time.deltaTime);

    currentRotationAnglePitch = Mathf.LerpAngle(currentRotationAnglePitch, wantedRotationAnglePitch, RotationDamping * Time.deltaTime);

    currentRotationAngleRoll = Mathf.LerpAngle(currentRotationAngleRoll, wantedRotationAngleRoll, RotationDamping * Time.deltaTime);

    var currentRotation = Quaternion.Euler(currentRotationAnglePitch, currentRotationAngleYaw, currentRotationAngleRoll);

    transform.position = Target.transform.position;
    transform.position -= currentRotation * Vector3.forward * Distance;

    transform.LookAt(Target.transform);
    transform.position += transform.up * Height;
}

图片:

在此处输入图像描述

标签: c#unity3dcamera

解决方案


如果您解释了您要做什么,我会更确定这个答案,但是您应该考虑朝Height方向currentRotation * Vector3.up而不是transform.up. 另外,currentRotation * Vector3.up在调用时考虑使用设置本地向上方向LookAt

transform.position = Target.transform.position;
transform.position -= currentRotation * Vector3.forward * Distance;

Vector3 currentUp = currentRotation * Vector3.up;
transform.LookAt(Target.transform, currentUp);
transform.position += currentUp * Height;

推荐阅读