【问题标题】:Trouble rotating vector inside unity无法在统一内旋转矢量
【发布时间】:2020-02-28 03:46:21
【问题描述】:

我正在制作一个游戏,您可以在其中旋转播放器并改变重力。我遇到的问题是实际上将播放器的旋转、播放器的键盘输入和当前的重力放在一起。

第 1 行(Quaternion.FromToRotation) 工作完全正常,直到重力下降(gravityDir(0, -1, 0)) 或上升(gravityDir(0, 1, 0)),在这种情况下,movementInput 的 y 分量将倒过来。

我不能只检查它是否是两者之一并将其翻转回来,因为我需要它能够逐渐从一个值更改为另一个值,或者处于不同角度之间(例如 (1, 1, 0) 例如)

movementInput 只是被放入一个向量中(w-s 为 x,a-d 为 z)。

gravityDir 是重力(0, -1, 0)的矢量,向下 (0, 1, 0) 向上 (1, 0, 0) 为正 x 方向等。

headAttach 是一个控制玩家头部的 GameObject,我在代码中获取它的 y 值来旋转运动输入向量,这样我就可以“朝我所面对的方向移动”。

movementInput = Quaternion.FromToRotation(gravityDir, Vector3.up) * movementInput;
movementInput = Quaternion.AngleAxis(headAttach.transform.localRotation.eulerAngles.y, transform.up) * movementInput;

rb.AddForce(movementInput * 5 * movementSpeed);

【问题讨论】:

    标签: c# unity3d quaternions


    【解决方案1】:

    在这种情况下不要使用FromToRotation,因为你关心的不仅仅是向上的方向。您还关心前进/右转的方向。

    改为使用LookRotation。您需要找到与玩家正在注视的方向(我假设是headAttach.transform.forward)最接近的方向,该方向与重力方向垂直。您可以为此使用交叉产品。然后,将该方向用于 LookRotation 的 forward 参数,将与重力相反的方向用于 up:

    Vector3 movementInput = Vector3.forward * Input.GetAxis("Vertical") 
            + Vector3.right * Input.GetAxis("Horizontal");
    
    Vector3 upDir = -gravityDir;
    Vector3 lookDir = headAttach.transform.forward;
    
    Vector3 rightDir = Vector3.Cross(upDir, lookDir);
    Vector3 forwardDir = Vector3.Cross(rightDir, upDir);
    
    movementInput = Quaternion.LookRotation(forwardDir, upDir) * movementInput;
    
    rb.AddForce(movementInput * 5 * movementSpeed);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多