- Home /
Rigidbody angularvelocity shortest way
I'm using rigidbody velocity to move around and I use mouse clicks to check which direction should my player character go
I don't know how to check when my rigidbody should make turn left or right, what should the if statement look like to choose the shortest way because if I use only right turn and then I click somewhere where left turn could do just 10 degrees to the left and it's done it still makes right turn and does 170 degrees to the right to meet the condition to stop.
if(Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 1000f))
{
clickPos = hit.point;
clickPos.y = 0f;
}
//playerRigidbody.velocity = Vector3.zero;
playerToMouse = clickPos - transform.position;
playerToMouse.y = 0f;
newRotation = Quaternion.LookRotation(playerToMouse);
Debug.Log(Quaternion.Angle(newRotation, playerRigidbody.rotation));
//playerRigidbody.MoveRotation(newRotation);
if( something >= something) <--- what should I put here?
{
playerRigidbody.angularVelocity = Vector3.down * ANGULARRIGID;
}
else
{
playerRigidbody.angularVelocity = Vector3.up* ANGULARRIGID;
}
}
Answer by Bunny83 · Dec 01, 2015 at 01:45 PM
Simply this:
if (Vector3.Dot(transform.right, playerToMouse) > 0)
You might need to swap the greater-than with a lower-than.
The dot product returns 0 when the two vectors are perpendicular to each other. If they point in the same direction it returns a positive value if it points in the opposite direction a negative value. So if it's positive you should turn right.
It works perfectly, thank you very much :) I were using the Quaternion.Angle before but it just doesn't fit that role :) A lot work ahead of me if I didn't make it work but I'm glad that you helped me fast. Cheers!
Your answer