Search code examples
javascriptthree.jssimulationphysicsgame-physics

Physics simulation basics


Consider a 3D solar system simulation.

My simulation loop:

[Calculate new positions]->[Render]->[Calculate new positions]->[Render] etc....

This loop runs at, say, 25FPS.

A planet in my simulation is travelling very fast towards the sun (on a collision course). Lets look at the simulation loop:

  1. Position is calculated for the planet and the sun (they have not collided yet, but are very close to each other).
  2. Scene is rendered.
  3. Since FPS is not infinite, there is a small pause before the next iteration.
  4. Position is calculated for planet and sun - and here's the crux of my problem - they have not collided because during the 'small pause' the planet has travelled 'through' the sun and their positions are now a large distance apart. The collision detection algorithm does not detect any collision.

The only solutions I can see here are:

  • raise the FPS
  • lower the speeds of my planets (lower the gravitational constant??)
  • have a separate simulation loop than runs alongside the render loop, but faster

For anyone interested, I'm using three.js.


Solution

  • Happens with projectiles in shooter games. One solution is to have your movement stage shoot a line segment along the forward path to see if it would hit anything before the next frame. That assumes that only the one object is moving rapidly though. I suppose you could also run a segment between the last position and the new position although I've not done it that way myself. I've also had success just extending my collider definition forward into an ellipse that covers the unchecked area.