hunar4321 / particle-life

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

Particle Weights #56

Open BetterBelle opened 1 year ago

BetterBelle commented 1 year ago

I think having particle weights would be cool. Obviously, you made it without weights for simplicity, but I think it could be an interesting addition.

AnasQiblawi commented 1 year ago

I was thinking maybe we should add a GUI section for additional physics options.

Maybe we treat empty void as fluid. perhaps add gravity. or even perform the calculations using different formulae.

and give particles more properties so they can be used in these options

I believe that would be cool.

studiosoho commented 1 year ago

You can add it easily by changing this formula here: F = (g * 1) / d;

Change the "1" with a Long parameter.

Every atom must have a mass, so change the property of them: atom = (x, y, c, m) => { return { x: x, y: y, vx: 0, vy: 0, color: c, mass: m }; };

studiosoho commented 1 year ago

I have made a version with mass:

<canvas id="life" width="500" height="500"></canvas> <script> //Hunar Ahmad @ brainxyz m = document.getElementById("life").getContext("2d"); draw = (x, y, c, s) => { m.fillStyle = c; m.fillRect(x, y, s, s); }; atoms = []; atom = (x, y, c, m) => { return { x: x, y: y, vx: 0, vy: 0, color: c, mass: m }; }; random = () => { return Math.random() * 400 + 50; }; create = (number, color, mass) => { group = []; for (let i = 0; i < number; i++) { group.push(atom(random(), random(), color, mass)); atoms.push(group[i]); } return group; }; rule = (atoms1, atoms2, g) => { for (let i = 0; i < atoms1.length; i++) { fx = 0; fy = 0; for (let j = 0; j < atoms2.length; j++) { a = atoms1[i]; b = atoms2[j]; dx = a.x - b.x; dy = a.y - b.y; d = Math.sqrt(dx * dx + dy * dy); if (d > 0 && d < 80) { F = (g * 1) / d; fx += F * dx; fy += F * dy; } } a.vx = (a.vx + fx) * 0.5; a.vy = (a.vy + fy) * 0.5; a.x += a.vx; a.y += a.vy; if (a.x <= 0 || a.x >= 500) { a.vx *= -1; } if (a.y <= 0 || a.y >= 500) { a.vy *= -1; } } }; yellow = create(200, "yellow", 0.8); red = create(200, "red", 0.9); green = create(200, "green", 1.1); update = () => { rule(green, green, -0.32); rule(green, red, -0.17); rule(green, yellow, 0.34); rule(red, red, -0.1); rule(red, green, -0.34); rule(yellow, yellow, 0.15); rule(yellow, green, -0.2); m.clearRect(0, 0, 500, 500); draw(0, 0, "black", 500); for (i = 0; i < atoms.length; i++) { draw(atoms[i].x, atoms[i].y, atoms[i].color, atoms[i].mass); } requestAnimationFrame(update); }; update(); </script>