The Law of Cosines

One of the fancy things I wanted to do in Space Engineers was build my own "autopilot" functionality.  There's an existing one based on the "Remote Control" block but it doesn't offer the kind of fine-tuning I wanted.  Specifically it uses too much fuel by getting up to speed and then keeping both the forward and backward thrusters active instead of treating space like space and getting up to speed and then coasting until it's time to slow down.

In this video I review the code I came up with for orienting the spacecraft towards the waypoint using the "Law of Cosines".  Most of us learned (or at least were taught) the Pythagorean Theorem in school, and so basically understand that when you have a right-angle triangle, the shorter sides a2 + b2 = c2, the longer side.  What most of us probably didn't learn is that there's a more generic version of this for other triangles that are NOT at right angles.  This means that by plugging in the X and Z coordinates of our current location relative to a waypoint, we can use this generic "Law of Cosines" to solve for the angle between our current heading and the waypoint and then turn the spacecraft (using the gyroscope blocks) until that angle reaches 0°.

All of that resulted in this C# script interfacing with the Space Engineers Scripting API to rotate a spacecraft to orient towards a waypoint, a critical element in any autopilot functionality.