Unity:以 45 的偏移量旋转 Gizmo

Get*_*awn 3 c# matrix quaternions unity-game-engine

我正在绘制两个线框球体,我想跟随玩家周围。然而,当玩家移动时,两个小玩意儿会跟随移动,而当我旋转时,只有其中一个小玩意儿会旋转。

损坏的 gizmo 代码如下所示,它的偏移量应该为 45:

void OnDrawGizmosSelected() {
  Gizmos.color = new Color(1, 0, 0);

  Gizmos.matrix = Matrix4x4.TRS(transform.position, Quaternion.Euler(transform.rotation.x, transform.rotation.y + 45, transform.rotation.z), Vector3.one);
  Gizmos.DrawWireSphere(Vector3.zero, 5f);
}
Run Code Online (Sandbox Code Playgroud)

作为参考,这里是带有两个小玩意的整个块:

void OnDrawGizmosSelected() {
  Gizmos.color = new Color(1, 0, 0);
  // This one works
  Gizmos.matrix = Matrix4x4.TRS(transform.position, transform.rotation, Vector3.one);
  Gizmos.DrawWireSphere(Vector3.zero, 5f);

  // This one does not work
  Gizmos.matrix = Matrix4x4.TRS(transform.position, Quaternion.Euler(transform.rotation.x, transform.rotation.y + 45, transform.rotation.z), Vector3.one);
  Gizmos.DrawWireSphere(Vector3.zero, 5f);
}
Run Code Online (Sandbox Code Playgroud)

默认不旋转(我希望它在旋转时保持不变)

默认旋转

绕 Y 轴旋转

Y 轴旋转

Fre*_*erg 5

Quaternion有 4 个分量,x、y、z 和 w。

仅仅将 x、y 和 z 输入Quaternion.Euler不会给您预期的结果。

相反,使用transform.rotation.eulerAngles

void OnDrawGizmosSelected()
{
    Gizmos.color = new Color(1, 0, 0);
    // This one works
    Gizmos.matrix = Matrix4x4.TRS(transform.position, transform.rotation, Vector3.one);
    Gizmos.DrawWireSphere(Vector3.zero, 5f);

    // This one works now :)
    Gizmos.matrix = Matrix4x4.TRS(transform.position, Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y + 45, transform.rotation.eulerAngles.z), Vector3.one);
    Gizmos.DrawWireSphere(Vector3.zero, 5f);
}
Run Code Online (Sandbox Code Playgroud)

编辑:

好的,Y 值已修复,但 X 和 Z 仍然损坏。他们移动,但方向不正确。

然后尝试

    // This works even better
    Gizmos.matrix = Matrix4x4.TRS(transform.position, transform.rotation, Vector3.one) * Matrix4x4.Rotate(Quaternion.Euler(0, 45, 0));
Run Code Online (Sandbox Code Playgroud)