hunar4321 / particle-life

A simple program to simulate artificial life using attraction/reuplsion forces between many particles
MIT License
2.98k stars 297 forks source link

Bounds checking is insufficient #4

Closed redblobgames closed 1 year ago

redblobgames commented 2 years ago

The current JS code and the C++ code too are checking

    if(a.x <= 0 || a.x >= 500){ a.vx *=-1 }
    if(a.y <= 0 || a.y >= 500){ a.vy *=-1 }

This is not enough to keep the particles inside the box. You can test this by checking how many are inside the box:

    const inRange = (p) => 0 <= p.x && p.x < 500 && 0 <= p.y && p.y < 500
    console.log(yellow.filter(inRange).length, red.filter(inRange).length, green.filter(inRange).length)

The reason is that it reverses the velocity but doesn't apply right away, so the next update the velocity might change to be the wrong sign again. To ensure they stay inside the box you need to have them bounce on this frame and change the velocity, like this:

        WIDTH = 500
        HEIGHT = 500
        if (a.x < 0) { a.x = -a.x; a.vx *= -1; }
        if (a.x >= WIDTH) { a.x = 2*WIDTH - a.x; a.vx *= -1; }
        if (a.y < 0) { a.y = -a.y; a.vy *= -1; }
        if (a.y >= HEIGHT) { a.y = 2*HEIGHT - a.y; a.vy *= -1; }

With this code, the particles all stay inside the box. They might get be pushed out to the outer edges of the box but at least all of them stay on screen.

abnormalhare commented 1 year ago

Please fix this

redblobgames commented 1 year ago

It looks like it's fixed in the JS https://github.com/hunar4321/life_code/blob/main/particle_life.html#L163

gagzilla commented 1 year ago

The current code doesn't seem to do the right thing. It "resets to the wall" (Setting to zero and width/height at boundaries) and that creates some interesting and unusual artifacts near the border- which are more pronounced if you only use one "color" and a small number of atoms. Understandably, as the velocity vector increases- so does the strangeness. I think resetting to the "reflected" state (as pointed in the code by @redblobgames) is the better approach to minimize these effects.

dangarfield commented 1 year ago

Fix added and also x4/5 times performance improvement for JS version - https://github.com/hunar4321/particle-life/pull/27

hunar4321 commented 1 year ago

bounds checking fixed for C++ too