【问题标题】:how to rotate object according to the rotation of the camera?如何根据相机的旋转来旋转物体?
【发布时间】:2021-09-08 02:34:41
【问题描述】:

我想根据相机的旋转来旋转玩家的身体。像FPS游戏。

步骤>>

  1. 当摄像头朝下时,我可以在摄像头下方看到我的身体。
  2. 我的身体必须跟随摄像头的位置。
  3. 我的身体也必须跟随摄像机旋转。
  4. 所以当我朝下摄像头时,我可以在任何地方看到我的身体。

这是我的代码。它附加到身体(我必须旋转的对象)。

 private void Update()
    {
        transform.position = arCamera.transform.position;
        transform.rotation = arCamera.transform.rotation;
    }

我想在相机朝下时看到我的身体,但身体会随着相机旋转,所以我永远看不到身体。我怎么能看到它? ;( 请帮忙!

【问题讨论】:

  • 请编辑问题以将其限制为具有足够详细信息的特定问题,以确定适当的答案。
  • 传统上,FPS 根本不渲染玩家的身体(对于玩家而言),尽管它们通常会提供某种投影。 (星际公民是其中最著名的例外之一)
  • 您能举个例子说明您希望发生的事情吗?

标签: c# unity3d arcore


【解决方案1】:

听起来你希望你的身体只复制绕 Y 轴的旋转。

用向量计算比用四元数旋转更容易;)

private void Update()
{
    transform.position = arCamera.transform.position;

    // Take your camera forward vector
    var camForward = arCamera.transform.forward;
    // erase the Y component
    camForward.y = 0;
    // and now make your body look into this flattened direction
    transform.rotation = Quaternion.LookDirection(camForward, Vector3.up);
}

另见Quaternion.LookDirection

这当然有一个小缺陷:当相机向上或向下看超过 90° 时,身体会翻转到相反的方向。因此,您要么想要限制相机旋转,要么想出不同的方法。

例如假设人类在Z 轴上旋转(倾斜)头部超过 90° 更困难,您也可以这样做

private void Update()
{
    transform.position = arCamera.transform.position;

    // Take your camera forward vector
    var camRight = arCamera.transform.right;
    // erase the Y component
    camRight.y = 0;
    // and now align the body's right axis with this flattened direction
    // Since we never touch the object's up vector this works without problems
    transform.right = camRight;
}

【讨论】:

  • 感谢您的热情回复!但这不是我想要的结果......当我旋转任何轴时,身体会奇怪地旋转。我希望身体跟随相机的位置和旋转值。您的代码在 Y 轴上旋转良好,但如果您在不同的轴上旋转,您会得到一个奇怪的结果……身体应该始终像连接到相机底部一样移动。因此,即使相机超过 90 度,我也总能看到身体的正面。我不知道我解释得好不好……;(祝你有美好的一天!
猜你喜欢
  • 2021-04-15
  • 2012-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-28
  • 1970-01-01
相关资源
最近更新 更多