I want to calculate a target’s bearing to a ship relative to the ship’s orientation. By bearing, I mean a range of 360 degrees in the XZ plane and a range of +/-90 degrees in the YZ plane. Some thing like this: 90,-45 should indicate you need to turn your ship to the right 90 degrees and pitch down 45 degrees. Of course, if you roll your ship, instead, those values would change to reflect the bearing relative to the ship’s new orientation.
I am having trouble working this out. I have tried using Vector3.Dot, but I can’t seem to get it to calculate only the angle relative to the plane needed (either only the XZ plane or only the YZ plane). Can anyone suggest how to accomplish this?
First, transform the position of the target into local coordinates using Transform.InverseTransformPoint(). Then, perform a Cartesian-to-spherical-coordinate conversion to yield the angles.
Post back if you need more details.
I’m on my way out the door to do field work, so I can’t look up Cartesian-to-spherical-coordinate conversion, so if you don’t mind, could you just summarize what that means. I can kind of guestimate the meaning, but if there is a process, I’d appreciate a brief summary. Otherwise, I can loko it up when I get back in.
Either way, thanks for pointing me in the right direction (pun totally intended).
Cartesian-to-spherical-coordinate conversions generally look something like this (although there are variations):
yaw = atan2(x, z);
pitch = atan2(y, sqrt(x*x+z*z));
I think those are the right conventions for your particular case, but I could have gotten something switched around somewhere. You may also want to handle the cases of the target position being more or less directly above or below separately, since in those cases the ‘yaw’ angle can’t be uniquely determined.
Yes, sir. Thank you. That did the trick. The only problem with what you had was that the x and the z needed to be switched for the yaw calculation. Thanks so much.
Oops, yeah, they were backwards (I edited the post so it’ll be correct for anyone else who reads the thread).
Anyway, glad it worked for you 