I am working on a 3D orbit simulation, in which an object is moving around the surface of the earth (a sphere).
I managed to get the orbits working using a function from this Stack Overflow answer. Each frame, I increase the distance variable of the object, and pass it into the function along with its start latitude, longitude and angle. The function gives me back a new latitude and longitude, which I convert to cartesian coordinates using this formula.
This works perfectly, and the object orbits around the sphere as desired. The problem I am facing now is aligning / rotating the object to face in the direction it is travelling in.
My attempt at doing this so far has been as follows:
- Point the object at the centre of the sphere. This can be easily done using the
Object3D.lookAt
function. This results in the object being parallel to the surface of the sphere. - Create an arbitrary axis vector from the centre of the sphere to the object.
- Rotate the object around said axis using the
Object3D.rotateOnWorldAxis
function.
This allows the object to be freely rotated, while keeping it flat against the surface of the sphere. If I set the rotation to 0Ď€
, it will simply always point north (towards the top of the sphere) regardless of its position.
If I set its rotation equal to its angle + π
(angle being one of the paramaters I pass into the orbit function mentioned earlier) it works, but only at the start. As the object travels around the sphere, the angle begins to drift further of its orbit, and when it reaches the opposite side, it is no longer pointing anywhere near to its direction of travel.
Interestingly, I found that setting the rotation equal to angle * -1
gives the opposite result, with it pointing incorrectly at the start, and aligning as it reaches the opposite side of the sphere.
There must be some easy way to do this (most likely using trigonometric functions) which I cannot think of. Any help will be greatly appreciated!