-1

我正在尝试将我的游戏对象旋转到它正在移动的方向。我没有使用 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; 

        }
    }
}

关于如何实施轮换的任何建议?我完全被难住了

4

3 回答 3

3

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

所需积分:

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

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

现在使用反正切来求角度。

angle = arctan(y/x)

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

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

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

于 2014-09-10T02:45:31.150 回答
0

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

就像是:

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

假设playerGameObject 前向方向为 Z ,对您的代码进行了快速测试并且该代码有效。

于 2014-09-10T06:35:58.750 回答
0

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

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

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

于 2014-09-10T21:15:06.937 回答