Search code examples
javaparticles

How do those java sand games keep track of so many particles?


Can anyone shed any light on how a program like that might be structured?

What java classes would they employ to keep track of so many particles and then check against them for things like collision detection? Particles need to know what particles they are next to, or that they're not next to anything so they can fall etc.

Here's an example, incase you're not sure what a sand game is.


Solution

  • Arrays, mainly.

    • A one-dimensional array of actively moving grains, represented by two coordinates (and possible a velocity if you want gravitational acceleration).
    • A two-dimensional array of bools (or colours), representing the fixed parts of the world.

    The simplest physics model is to remove a grain once it is at rest (e.g. when the world positions below, below to the left and below to the right are filled): instead, the corresponding world coordinate is filled in. This keeps the calculations manageable. Allow a grain to shift down if either the left or right below world coordinate is free. Grain collisions between moving grains can be ignored without loss of much verisimilitude.

    (I can't quite get over how much CPU power we've got to spare these days!)