- Home /
Rotate rigidbody towards mouse position
Hi all,
I'm trying to get the tanks tutorial to rotate the tank to face the cursor instead of using the A and D keys on the keyboard,
currently the A and D keys rotate the y axis of the rigidbody
// Determine the number of degrees to be turned based on the input, speed and time between frames.
float turn = m_TurnInputValue * m_TurnSpeed * Time.deltaTime;
// Make this into a rotation in the y axis.
Quaternion turnRotation = Quaternion.Euler (0f, turn, 0f);
// Apply this rotation to the rigidbody's rotation.
m_Rigidbody.MoveRotation (m_Rigidbody.rotation * turnRotation);
I don't want to simply rotate the transform as that seems to disable the W and S movement which I would like to keep in tact.
Thanks for any help.
I've managed to get this somewhat working using this code. Although the results aren't as accurate as I would like... the tank faces the cursor but not overly accurately, does anyone know how to achieve better results, I am very new to the physics stuff.
private void Turn ()
{
objectPosition = camera.WorldToViewportPoint(transform.position);
mousePosition = (Vector2)camera.ScreenToViewportPoint(Input.mousePosition);
float angle = AngleBetweenTwoPoints(objectPosition, mousePosition);
// Deter$$anonymous$$e the number of degrees to be turned based on the input, speed and time between frames.
//float turn = m_TurnInputValue * m_TurnSpeed * Time.deltaTime;
// $$anonymous$$ake this into a rotation in the y axis.
//Quaternion turnRotation = Quaternion.Euler (0f, turn, 0f);
// Apply this rotation to the rigidbody's rotation.
m_Rigidbody.rotation = Quaternion.Euler(new Vector3(0, angle, 0));
}
float AngleBetweenTwoPoints(Vector2 a, Vector2 b)
{
return $$anonymous$$athf.Atan2(b.y - a.y, a.x - b.x) * $$anonymous$$athf.Rad2Deg;
}
Your answer
Follow this Question
Related Questions
How to make a player rotate in a direction with a slope of the ground. 0 Answers
How to rotate camera around 3D object without breaking camera rotation 0 Answers
How can I rotate my player with a Joystick? 0 Answers
3D top down shooter mouse follow inaccurate. 0 Answers
How can I make an object rotate to a specific euler angle? 1 Answer