I am working on an project to simulate physics/gravity in space and one part is to predict orbits and display certain information, one of many are periapsis and apopasis (closest and most remote point of an orbit). The easiest way to achieve this is to find the point where the approaching velocity of the object in orbit relative to the stationary object is 0 but because the amount of calculations per second is limited it almost never happens that the value is exact 0 - so my thought was to compare every loop if the sign of the current value and the value the loop before has changed.
The code looks similar to this:
ArrayList orbit = new ArrayList();
orbit.Add(newValue);
//In case the sign changes - to +
if(
orbit.Count >= 2 &&
physics.getVelocity(orbit[orbit.Count-1], otherObject) == Math.Abs(physics.getVelocity(orbit[orbit.Count-1], otherObject) &&
physics.getVelocity(orbit[orbit.Count-2], otherObject) != Math.Abs(physics.getVelocity(orbit[orbit.Count-2], otherObject)
)
//In case the sign changes + to -
if(
orbit.Count >= 2 &&
physics.getVelocity(orbit[orbit.Count-1], otherObject) != Math.Abs(physics.getVelocity(orbit[orbit.Count-1], otherObject) &&
physics.getVelocity(orbit[orbit.Count-2], otherObject) == Math.Abs(physics.getVelocity(orbit[orbit.Count-2], otherObject)
)
But sometimes it does not seem to work so I debuged the variable and could not find any mistakes there were always patterns like:
Value (1): -0.4523452
Value (2): 1.2435235
or
Value (1): 0.4523452
Value (2): -1.2435235
But the algorithm ignored some of the events but to my observation only if the numbers were close to 0 (like above) but if it looks like this:
Value (1): 64.904534
Value (2): -7.3456800
it is fine and I could not figure out why. I hope someone can help me - if there are any questions left, please ask :)