Hi there, I realise this may have been asked before but this is seriously driving me crazy.
Its like this. In this test scenario case, I have a projectile that keeps moving z-positive forward, i.e. a straight line.
Now, in a test scenario:
Projectile Origin = 0,0,0
Target Position = 45, 25, 53
Basic math tells me that I can just use arc tangents to calculate the angle, so for the projectile to face towards the target and hit it at that specific spot:
X rotation = arctan(25/53)
Y rotation = arctan(45/53)
To me, this is solid math, but even using this, my projectile NEVER hits the target! Its always too high! I really don’t understand what is going on, and it’s driving me nuts.
Before somebody answers use LookAt, I can’t because I need my projectile to have a bit of a random spray towards the target.
At the moment, I have a cheap work-around which is to make a duplicate transform with the same position as the projectile’s position, using LookAt on it and taking the rotation information from there.
It solves my problems, but I’m wondering why this is :x
Just multiply your returned angle with this constants to convert rad into degree or vice versa.
btw Mathf provides the Mathf.Atan2 function that does the 4-quadrant correction and returns an angles between 0 and 2*PI (aka 360°)
edit
atan and atan2 are 2d-functions. They only work in triangles. That's not a problem because you can always project 3d coordinates to a 2d surface or plane. The problem is that the rotation is done in 3 steps:
rotate around global z - axis
rotate around global x - axis
rotate around global y - axis
Rotating around the global axes is the same as the reversed rotation order around local axes:
rotate around local y - axis
rotate around local x - axis
rotate around local z - axis
So lets say y-rotation is the first one (heading / yaw). That one we can simply project onto the x-z-plane so just use the relative x and z coordinates with atan / atan2.
The second one is the x-rotation (pitch). This one you can't simply project onto x-y-plane or y-z-plane because the plane where our triangle is located is rotated by the y-rotation. You have to use the rotated leg. The y-value is not affected by the y rotation so we just need the second value corrected.
All we need is the Pythagorean theorem. I've created a small test script with two versions
MyLookAt(): calculated the hypotenuse "manually"
MyLookAt2(): uses the Vector3 class to calculate the hypotenuse.