在 Unity 中经常会遇到这样的需求:让某个角色旋转至面向一个目标点,比如玩家需要面向一个敌人。实现的思路通常有下面三种。

三种常见做法

  • transform.LookAt
  • Quaternion.LookRotation
  • 用原始的数学关系直接计算旋转角

用数学关系计算的示例代码

下面是一段用最基础的三角函数直接推导目标朝向的 C# 示例,演示如何把角色旋转到指向目标点的方向。

  /// <summary>
                    /// @brief turn rotation to the target position
                    /// </summary>
                    public void rotateToPosition(Vector3 pos_target)
                    {
                        float delta_x = transform.position.x - pos_target.x;
                        float delta_z = transform.position.z - pos_target.z + 0.01f;
                
                        //revise the angle 0-180 and 180-360
                        float delta = delta_z < 0 ? 0 : 180;
                
                        transform.rotation = Quaternion.Euler(transform.rotation.x,
                                Mathf.Atan(delta_x / delta_z) * 180.0f / Mathf.PI + delta
                                         , transform.rotation.z);
                
                    }