I’m revisiting my turret code as I’ve not got a “satisfactory” solution so far. The “usual” setup, immobile base, turret that rotates on one axis (left/right), gun which rotates in another axis (up/down). The fly in the ointment being the need to make this work regardless of the base’s orientation (i.e. it’ll work on the underside/top/side of a blimp/plane/tank/whatever).
Ideally the gun and turret wouldn’t know about each other, and be governed by their own scripts independently (previous solutions all had to know about all the parts of the turret which I’m not a fan of).
// "target" is a vector3 position
// "axis" is one of "transform.up" "transform.right"
// caluclates a point on the local plane
distanceToPlane = Vector3.Dot(axis, target - transform.position);
planePoint = target - (axis * distanceToPlane);
Quaternion rot = Quaternion.LookRotation(planePoint - transform.position, axis); // issue appears to be here
transform.rotation = Quaternion.RotateTowards(transform.rotation, rot, turretDegreesPerSecond * Time.deltaTime);
when this is applied to the turret (or gun, looks silly but works) and axis set to “transform.up” it works perfectly; and rotating the base of the turret also doesn’t upset the “left/right” rotation.
when this is applied to the gun (or turret, looks even more silly) and the axis set to “transform.right” things go awry.
(magenta line is planePoint-transform position, blue line is transform.forward, magenta, red and blue are in the same plane, all 90degs from green “up” (transform.up), small cyan arrows indicate resulting movement)
(yellow line is planePoint-transform position, blue line is transform.forward, green, yellow and blue are in the same plane, all 90degs from red “up” (transform.right), small cyan arrows indicate resulting movement)
(quick gif to show the planepoints caluclating correctly, last line in the code above is commented out to stop anything being actioned)
(orthographic view from front, red line is “transform.right” and should be the axis the gun is rotating around, target is in the same plane as the gun’s transform.forward and only moving up/down, planepoint vaguely visible inside the target)
as you can see from the gif when “upwards” in the LookRotation line is set to “transform.right” the resulting rotation isn’t only around “transform.right” but all three axis allowing the gun move incorrectly.
I’m having trouble seeing how/why this is the case. It should be the same calculation on a different set of axis (imagine knocking the tank in the first picture on it’s right side, you should get the exact same line layout as the second picture…)
If it was some sort of inaccuracy creeping in wouldn’t it also break when the axis is set to transform.up?