- Home /
Calculate launch angle based on launch direction
I'm working with a setup like this:
Where the vectors all start at transform.position and end as follows:
Black: transform.position + HandlePosition
Blue: transform.position + Vector2.right
White: transform.position - HandlePosition.normalized
The idea is that i can move the red handle around to change the White vector (the launch direction of the object).
Now what I would like to get is the angle between the White and Blue vectors.
I want to get this angle so that I can calculate the trajectory of the object and display a trajectory line.
Edit:
Given the example shown on the picture, I would expect an angle of about 45 degrees.
Answer by Malyglut · May 21, 2019 at 05:09 PM
The solution was to calculate a new vector based on the White vector and then use it in the Mathf.Atan2 method.
Vector3 newVector = transform.position - White;
float angle = Mathf.Atan2(newVector.y, newVector.x) *Mathf.Rad2Deg;
This however gives values ranging from -180 to 180, to convert this to a 0 - 360 degree value I simply added 180 to the result of previous calculation.
angle+= 180;
This works nicely for what I'm trying to do.
Thanks to @Pangamini for guiding me in the right direction.
Note that adding 180° will not give you the angle between your white and blue vector when using the white direction vector but between your blue and black line. So you essentially use your "HandlePosition" which doesn't seem to be a position but a relative direction vector.
Since "White" is equal to transform.position - HandlePosition.normalized
and your "newVector" is transform.position - White
you just did calculate:
newVector = transform.position - (transform.position - HandlePosition.normalized)
This is the same as
newVector = HandlePosition.normalized
So you calculate the angle between the blue and black line and then add 180°. btw: Atan2 doesn't need a normalized vector.
Yes, you're completely right. I missed that. Is what I'm doing right now a very hacky approach? If so, what would be the correct way of tackling the problem of calculating the angle between Blue and White?
Well, the white direction vector is just
Vector3 white = -HandlePosition;
The angle is just
float angle = $$anonymous$$athf.Atan2(white .y, white .x) * $$anonymous$$athf.Rad2Deg;
To make the range be 0 to 360 ins$$anonymous$$d of -180 to 180 just do this afterwards:
if (angle < 0)
angle += 360;
Answer by Pangamini · May 21, 2019 at 04:51 PM
Check out Mathf.Atan2
Which vectors would I input into the $$anonymous$$athf.Atan2?
"Return value is the angle between the x-axis and a 2D vector starting at zero and ter$$anonymous$$ating at (x,y)."
btw: Atan2 is not specific to Unity. It exists in almost any math library. It just does arctan(y/x) and does a quadrant selection depending on the signs of x and y. It also handles problematic cases like the case when x == 0.
Yeah, I am kind of happy that Unity didn't invent their own off-world math :D