Unity3D跟随Sphere Player相机旋转

时间:2018-11-05 09:55:50

标签: unity3d

嗨,我正试图让我的相机跟随我的播放器(Sphere)移动。我有相机跟随玩家,但是当球体旋转时,相机也随之旋转。那不是我要找的东西。我需要相机保持在球体上并在转动时旋转。到目前为止,这是我的代码:

编辑:我正在寻找的东西就像您在vid中看到的一样。球体旋转时相机旋转的位置,所以它一直在它后面。 https://www.youtube.com/watch?v=jPAgPQi1l0c

using UnityEngine;
using System.Collections;

public class TransformFollower : MonoBehaviour
{
[SerializeField]
private Transform target;

[SerializeField]
private Vector3 offsetPosition;

[SerializeField]
private Space offsetPositionSpace = Space.Self;

[SerializeField]
private bool lookAt = true;

private void Start()
{
    offsetPosition = new Vector3(-3, -2, 0);
}
private void Update()
{
    Refresh();
}

public void Refresh()
{
    if (target == null)
    {
        Debug.LogWarning("Missing target ref !", this);

        return;
    }

    // compute position
    if (offsetPositionSpace == Space.Self)
    {
        transform.position = target.TransformPoint(offsetPosition);
    }
    else
    {
        transform.position = target.position + offsetPosition;
    }

    // compute rotation
    if (lookAt)
    {
        transform.LookAt(target);
    }
    else
    {
        transform.rotation = target.rotation;
    }
}
}

2 个答案:

答案 0 :(得分:2)

您应该实现以下逻辑:

创建一个空的gameObject:Character,将其作为子元素:Camera,Sphere

当您移动时,只需变换角色,因此“照相机”和“球体”以完全相同的方式变换。

现在,当您只想旋转球体而不旋转相机时,只需在球体中应用旋转(或其他任何旋转)即可。 为此,您可以在脚本中传递角色和球体。 因此,移动变换将仅应用于球体中的角色和任何自定义移动。

尼克

答案 1 :(得分:1)

您是否亲自编写了此代码?

如果lookat为真,它将看起来像您想要的那样。如果为假,则按照您的描述进行操作。

只需在编辑器中查看并选中“ look at”框即可。

如果您不想使用它,可以通过删除lookat变量并替换

将其从代码中删除。
// compute rotation
if (lookAt)
{
    transform.LookAt(target);
}
else
{
    transform.rotation = target.rotation;
}

作者

// compute rotation
transform.LookAt(target);

编辑更多说明:

在代码中,您有两个选择:lookatoffsetPositionSpace

offsetPositionSpace基本上可以是两个值:

  • Self ->相机将始终位于播放器后面(如果旋转播放器,它将移动到后面)
  • World ->相机将始终模仿玩家的移动(如果玩家旋转,相机将不会移动

LookAt也可以有两个值

  • true ->相机始终看着播放器
  • ->摄像头模仿玩家的旋转(如果玩家旋转,则摄像头会照此旋转并停止注视玩家)
相关问题