- Home /
Rotate an arrow object based on addedForce
Hi guys,
I'm adding force to a Rigidbody2D (ball) using the below lines of code
public class ThrowBall : MonoBehaviour {
public int speed;
Vector2 direction = new Vector2(1f,1f);
void throwBall(int speed, Vector3 direction){
GetComponent<Rigidbody2D>().AddRelativeForce(direction*speed);
}
}
How to get the angle in which this gameObject(ball) moves so that I can set the rotation of an arrow object to indicate the direction in which the ball is moving?
Answer by PatriceVignola · Aug 01, 2015 at 07:56 AM
You can get the angle in which your ball moves by simply calculating the angle between its velocity vector and the x axis (since you are in 2D). In Unity terms, this gives us:
float angle = Vector3.Angle(GetComponent<Rigidbody2D>().velocity, Vector2.right);
If you want the angle to be dependent on the direction (left or right) of the ball and keep it under 90 degrees, you can use tranform.right instead:
float angle = Vector3.Angle(GetComponent<Rigidbody2D>().velocity, transform.right);
Let me know if you have more questions.
Your answer
Follow this Question
Related Questions
Why is my GameObject rotation snapping to a certain angle when he reaches its destination? 2 Answers
rotation LookAt of 2D gameObject in 3D space 1 Answer
How do you AddForce to a rigidbody2D in the direction of a joystick? 0 Answers
Point an arrow at the mouse position, 2.5D 1 Answer
Using direction and Rigidbody2D.AddForce() to move towards object. 1 Answer