forked from hunar4321/particle-life
-
Notifications
You must be signed in to change notification settings - Fork 0
/
particle_life.html
60 lines (60 loc) · 1.59 KB
/
particle_life.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<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)=>{return{"x":x, "y":y, "vx":0, "vy":0, "color":c}}
random=()=>{return Math.random()*400+50}
create=(number, color)=>{
group=[]
for(let i=0; i < number; i++){
group.push(atom(random(), random(), color))
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")
red = create(200, "red")
green = create(200, "green")
update=()=>{
rule(green, green, -0.32)
rule(green, red, -0.17)
rule(green, yellow, 0.34)
rule(red, red, -0.10)
rule(red, green, -0.34)
rule(yellow, yellow, 0.15)
rule(yellow, green, -0.20)
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, 5)
}
requestAnimationFrame(update)
}
update();
</script>