繁体   English   中英

让相机跟随玩家对象在 3D 空间中的位置和旋转(Unity3d)

[英]Have camera follow player -object position and rotation in 3D-space (Unity3d)

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

为此,我从统一答案站点“窃取”并修改了此代码,它对 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;
}

图片:

在此处输入图片说明

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

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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM