I’ve been programming for a while now in unity and there has always been one thing i’ve avoided… and that’s Rotation and Quaternions. I’m not good with math so to come into the world of Quaternions is a little overwhelming. Im working on a script to allow a CWIS gun object to automatically track, target, and engage flying game objects. This however introduces the issue of rotating to face an object. Normally I could get away with a transform.lookat() statement but that wont work in this case. I need to individually assign the azimuth and elevation to the different parts of the gun system. I’ve managed to get a piece of code working for the azimuth:
There’s probably a better way to do this, but just offhand you could do this:
Vector3 directionToTarget = (ObjectToTrack.transform.position- gunAsmuth.transform.position).normalized;
float elevationAngle = Vector3.Angle( directionToTarget, lookPos.normalized );
Quaternion elevationRotation = Quaternion.Euler(elevationAngle,0,0);
// Then apply elevationRotation to the localRotation of the turret's barrel transform which should be a child object of the turret base.
This will only work for targets above the turret. If your turret can also aim down then you’ll need to multiply the angle by the sign of the dot product for the turret’s up vector and the directionToTarget Vector
Another thing to note is that your code will only work for turrets are on a flat surface. If they are on an angled surface then your lookPos won’t be correct and my solution for the elevation will also be incorrect.