C# 在二维空间中将旋转变换为运动方向
我试图旋转我的游戏对象,使其朝向移动的方向。我没有使用刚体。速度,我只是使用transform.position来移动对象。这是我的密码:C# 在二维空间中将旋转变换为运动方向,c#,unity3d,rotation,2d,gameobject,C#,Unity3d,Rotation,2d,Gameobject,我试图旋转我的游戏对象,使其朝向移动的方向。我没有使用刚体。速度,我只是使用transform.position来移动对象。这是我的密码: public GameObject player; void Update () { Vector3 _origPos = new Vector3(player.transform.position.x,player.transform.position.y, player.transform.position.z); if (Inpu
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;
}
}
}
关于如何实施轮换有什么建议吗?我完全被难住了你用三角学来做。你需要3个参考点,幸运的是你已经有了其中的两个 所需要点: A你要搬到哪里去。 B质量中心的当前位置。 C物体的尖端,前面。 计算从B到C的距离,称之为x。然后计算从B到A的距离,称之为y 现在使用“反切线”查找角度
angle = arctan(y/x)
然后将其应用于对象的旋转
使用世界坐标而不是本地坐标
如果使用Mathf求逆切线,请记住它使用弧度。我假设您将使用它来确定变换的方向 比如:
Quaternion rotation = Quaternion.LookRotation(moveDirection);
player.transform.rotation = rotation;
用你的代码做了一个快速测试,假设玩家的游戏对象朝前的方向是Z。这在我的2D游戏中得到了我想要的效果
transform.LookAt(new Vector3(touchPosition.x,touchPosition.y,transform.position.z), Vector3.up);
我使用了对象自己的position.z而不是touchPosition.z,因此它保持在它的2D轴上谢谢您的输入。所以在Unity3D中还没有预先制作的方法吗?他们已经看过了,但是从来没有给过我正确的结果,所以我使用上面的通用公式。马瑟夫会帮忙的