首页 > 解决方案 > 围绕一个游戏对象统一运行

问题描述

在 Unity 中,我有一个具有以下结构的相机

GameObject Pan
    => GameObject Rotation
       => GameObject Zoom
          => GameObject Camera (the component that have the camera script)

我有一个对象目标

GameObject target;

我想围绕该对象向所有方向旋转。就像它是一架飞行的飞机,所以我可以左右旋转。

我有以下代码

void ChangePosition()
{
    if(Input.GetAxis("Horizontal") != 0 || Input.GetAxis("Vertical") != 0)
    {
        if (target)
        {
            transform.RotateAround(target.transform.position, transform.right, -Input.GetAxis("Vertical") * speed);
            transform.RotateAround(target.transform.position, transform.up, -Input.GetAxis("Horizontal") * speed);

            rotationObject.transform.LookAt(target.transform.position);
        }
    }
}

当您仅向左或仅向上移动时,它的效果很好。

但是如果你同时移动展位,旋转就不再直观了。它还会在自己身上旋转相机。

我希望相机只向左或向上移动(所以在 2 轴上旋转,但从不在她自己身上)

我该如何解决?

标签: c#unity3dcamera

解决方案


我不喜欢使用RotateAround(),但它们是一个更简单的解决方案。首先修改您的层次结构,添加一个新对象作为您的旋转中心,并将其放在目标对象的中心。

GameObject Target (your target game object)
    => GameObject RotationCenter (local position: 0, 0, 0. The center of Target)
         => GameObject Camera

然后简单地旋转你新的游戏对象RotationCenter。这样的事情应该可以解决问题:

RotationCenter.Rotate(Input.GetAxis("Vertical") * speed, Input.GetAxis("Vertical") * speed);

推荐阅读