Skip to content

Particle pile algorithm

An answer to this question on Stack Overflow.

Question

I'm creating a game which has around 3000 particles that fall into a pile. The particles are each a pixel and i just use a boolean[][] to set and check which pixel is clear. Right now i am using this code

if (!isFalling(m)) {
    if (isClear(getX() + 1, getY()) && isClear(getX() + 1, getY() - 1))
        setX(getX() + 1);
    else if (isClear(getX() - 1, getY()) && isClear(getX() - 1, getY() - 1)
        setX(getX() - 1);
}

the problem is that this code gives me a very strict pyramid shape which doesnt look very natural. I want it to look something like salt would if you poured it into a pile. My question is, does anyone know of an algorithm or a better way to simulate particle piles? Any help would be greatly appreciated.

Solution: I have found a nice article here

Answer

So your function looks at particles which have settled to the bottom and asks if they can slide down the side, and then effects that motion if they can.

Do you have this in a loop? If so, you may be considering particles from the "bottom up" whereas the sliding motion may take place at any point on the pile. You could try shuffling the particle list prior to performing the loop, or repeatedly choosing random elements from the list until you get a low rate of settling.

In the case of a 2D array, you could try looping from different directions or finding other ways of mixing it up - again choosing pixels at random may not be a bad choice. Simulated annealing comes to mind.

Or, you could add a random check to your sliding condition. The particles should be semi-stable in their initial positions, so maybe there's only a 50% chance of them sliding down the side.

Hope this helps!