hunar4321 / particle-life

A simple program to simulate artificial life using attraction/reuplsion forces between many particles

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Bounds checking is insufficient

redblobgames opened this issue · comments

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.

Please fix this

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.

Fix added and also x4/5 times performance improvement for JS version - #27

bounds checking fixed for C++ too