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?
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.