Unity:跟随玩家的主摄像头想要正面朝上

Unity: Main Camera following player wants to be right side up

我有一个玩家围绕一个球体移动,我的相机跟随玩家。当我移过球体绝对顶部或底部的极点时,场景会快速旋转,以便相机(和场景)的向上方向保持在显示的顶部。有没有办法简单地将其关闭?我宁愿场景没有上下的全局概念,只是相对的上下。如果没有一个简单的方法,是否有一个不那么简单的方法来避免旋转?如果有帮助,这是我的 Update() 代码。谢谢!

void Update()
    {
        Vector3 waypointTunnelDirection = Geometry.Scale(waypoints[waypointIndex] - transform.position, 0.01f);
        Vector3 waypointSurfaceStepPosition = Geometry.Scale(transform.position + waypointTunnelDirection, 0.5f);

        transform.position = Geometry.Scale(Vector3.MoveTowards(transform.position, waypointSurfaceStepPosition, maxSpeed), 0.5f);
        if (Vector3.Distance(transform.position, waypoints[waypointIndex]) < 0.01f) {
            waypointIndex = (waypointIndex + 1) % waypoints.Length;
        }

        mainCamera.transform.position = Geometry.Scale(transform.position, 2.0f);
        Vector3 targetDirection = transform.position - mainCamera.transform.position;
        mainCamera.transform.rotation = Quaternion.LookRotation(Vector3.RotateTowards(mainCamera.transform.forward, targetDirection, 99, 99));
    }

首先将相机控制逻辑放在相机组件的更新函数中。通过这样做,您可以使相机模块化,因此可以更轻松地在其他游戏中重复使用。

不要为临时播放器使用球体,而是使用任何具有明显顶部和正面的对象来进行测试和调试。然后让你的玩家在世界各地移动,然后再处理相机逻辑,因为玩家方向对于正确定位相机是必要的。

要向前移动玩家,只需将其移动到 transform.forward,然后使用 Quaternion.LookRotation:

将玩家“向上”重新定向
void Update()
{
    transform.position = transform.position + transform.forward * Time.deltaTime * speed;

    Vector3 up = transform.position;     // Assuming the center of the sphere world is (0,0,0)

    Vector3 forward = Vector3.Cross(transform.right, up);
    transform.rotation = Quaternion.LookRotation(forward, up);
}

要旋转您的播放器,请围绕其自身旋转 transform.up Vector3:

transform.RotateAround(Vector3.zero, transform.up, angularSpeed*Time.deltaTime);

现在您可以在它的更新功能中更新您的相机:

public class Camera : MonoBehavior
{
    public GameObject player;
    public float camHeight;
    public float camDistance;

    void Update()
    {
        Transform pt = player.transform;

        // Set camera Position;
        Vector3 camOffset = -pt.forward * camDistance + pt.up * camHeight;
        transform.position = pt.position + camOffset;

        // Set camera orientation
        transform.LookAt(pt.position, pt.up);
    }
}