由于旋转,角色移动无法正常工作

时间:2017-09-15 22:18:45

标签: unity3d rotation unity5

所以基本上问题是,当我想旋转角色并移动它时,运动不会按预期正常工作。如果我的y坐标低于零,则角色向后移动而不是向前移动。所以基本上是相反的方向。此外,如果我的操纵杆坐标如下:y = 0,23和x = 0,8我的角色显示在该方向但向下移动.. PS:y和x值从0到1(单位圆) 但是如果我只是在不旋转角色的情况下移动角色,那么角色的移动就应该如此。

这是我目前的代码:

 void Update()
 {

     if (myX != leftController.GetTouchPosition.x || myY != leftController.GetTouchPosition.y) { //checks if player changed position.
         myX = leftController.GetTouchPosition.x;
         myY = leftController.GetTouchPosition.y;

         double rad = Mathf.Atan2(leftController.GetTouchPosition.y, leftController.GetTouchPosition.x); // In radians
         double deg = rad * (180 / System.Math.PI); // values from up right to up left : +0 to +180 and from down left to down right: -180 to -0

         double myRotAngle = 0;
         //calculating the specific angle in which the character should move
         if (deg < 0) {
             myRotAngle = 90 + ((deg * -1));
         } else if (deg >= 0 && deg <= 90)
             myRotAngle = 90 - deg;
         else if (deg >= 90 && deg <= 180)
             myRotAngle = 270 + (180 - deg);

         transform.localEulerAngles = new Vector3 (0f,(float)myRotAngle, 0f);//rotate

     }

     _rigidbody.MovePosition(transform.position + (transform.forward * leftController.GetTouchPosition.y * Time.deltaTime * speedMovements) +
         (transform.right * leftController.GetTouchPosition.x * Time.deltaTime * speedMovements) );//move
 }

1 个答案:

答案 0 :(得分:1)

问题是transform.forward是一个向量,指向你的变换(在这种情况下是你的角色)所面对的任何方向。

让我们说你的操纵杆给出(0,1)。您的代码将旋转角色朝向北方,然后沿着他们面向的方向行走。好。

让我们说你的操纵杆给出(0,-1)。你的代码会将角色旋转到面向南方,然后让它们沿着他们面对的相反方向行走。这将使你走向与(0,1)相同的方向!

如果你想要的是(0,1)总是移动字符North,而(0,-1)总是移动字符South,将transform.forward和transform.right改为Vector3.forward并且Vector3.right应该足够了:

Vector3 forwardMovement = (Vector3.forward * leftController.GetTouchPosition.y * Time.deltaTime * speedMovements);
Vector3 sidewaysMovement = (Vector3.right * leftController.GetTouchPosition.x * Time.deltaTime * speedMovements);

_rigidbody.MovePosition (transform.position + forwardMovement + sidewaysMovement);

我还将MovePosition行拆分为多个步骤,以便于阅读。

操纵杆的另一个选项是使垂直轴向前和向后移动角色,并使水平轴旋转它们:

void Update()
{
    float newRotation = transform.localEulerAngles.y + leftController.GetTouchPosition.x;
    transform.localEulerAngles = new Vector3 (0f,newRotation, 0f);

    Vector3 forwardMovement = (transform.forward * leftController.GetTouchPosition.y * Time.deltaTime * speedMovements);
    _rigidbody.MovePosition (transform.position + forwardMovement);
}
相关问题