【问题标题】:Transform rotation to movement direction in 2D space将旋转转换为二维空间中的运动方向
【发布时间】:2014-09-09 18:31:25
【问题描述】:

我正在尝试旋转我的游戏对象,使其朝向它正在移动的方向。我没有使用 Rigidbody.Velocity,我只是使用 transform.position 来移动对象。这是我的代码:

public GameObject player;

void Update () 
{
    Vector3 _origPos = new Vector3(player.transform.position.x,player.transform.position.y, player.transform.position.z);

    if (Input.touchCount > 0) 
    {
        // The screen has been touched so store the touch
        Touch touch = Input.GetTouch(0);
        if (touch.phase == TouchPhase.Stationary || touch.phase == TouchPhase.Moved) {
            // If the finger is on the screen, move the object smoothly to the touch position
            Vector3 touchPosition = Camera.main.ScreenToWorldPoint(new Vector3(touch.position.x, touch.position.y, 10));                
            transform.position = Vector3.Lerp(transform.position, touchPosition, Time.deltaTime);
            //transform.LookAt(new Vector3(touchPosition.x,touchPosition.y,0), Vector3.up);
            Vector3 moveDirection = gameObject.transform.position - _origPos; 

        }
    }
}

关于如何实施轮换有什么建议吗?我完全被难住了

【问题讨论】:

    标签: c# unity3d rotation 2d gameobject


    【解决方案1】:

    你用三角函数来做。您将需要 3 个参考点,幸运的是您已经拥有其中两个。

    需要积分:

    • A) 你要搬到哪里去。
    • B) 质心的当前位置。
    • C) 对象的尖端,前面。

    计算从 B 到 C 的距离,称它为 x。然后计算 B 到 A 的距离,称为 y。

    现在用反正切求角度。

    angle = arctan(y/x)
    

    然后将其应用于对象的旋转。

    使用世界坐标而不是本地坐标。

    如果您使用Mathf 表示反正切,请记住它使用弧度。

    【讨论】:

    【解决方案2】:

    我假设你会使用 Quaternion.LookRotation 来定位你的变换。

    类似:

    Quaternion rotation = Quaternion.LookRotation(moveDirection);
    player.transform.rotation = rotation;
    

    假设player GameObject 的前向方向是 Z,对您的代码进行了快速测试。

    【讨论】:

      【解决方案3】:

      这在我的 2D 游戏中得到了我想要的效果。

       transform.LookAt(new Vector3(touchPosition.x,touchPosition.y,transform.position.z), Vector3.up); 
      

      我使用对象自己的 position.z 而不是 touchPosition.z,以便它保持在它的 2D 轴上

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-01-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-30
        • 2013-05-26
        相关资源
        最近更新 更多