-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathverlet2.html
118 lines (105 loc) · 2.5 KB
/
verlet2.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
html, body {
margin: 0px;
}
canvas {
display: block;
position: absolute;
top: 0px;
left: 0px;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
</body>
<script type="text/javascript">
window.onload = function() {
var canvas = document.getElementById("canvas"),
context = canvas.getContext("2d"),
width = canvas.width = window.innerWidth,
height = canvas.height = window.innerHeight;
var points = [],
bounce = 0.95,
gravity = 0.5,
friction = 0.999;
var npoints = 200;
for ( let i = 0; i < npoints; i++ ) {
let rx = Math.floor(Math.random() * 100);
let ry = Math.floor(Math.random() * 100);
points.push({
x: rx,
y: ry,
oldx: rx - Math.floor(Math.random() * 18),
oldy: ry - Math.floor(Math.random() * 18)
});
}
update();
function update() {
updatePoints();
renderPoints();
requestAnimationFrame(update);
}
function updatePoints() {
for(let i = 0; i < points.length; i++) {
let p = points[i],
vx = (p.x - p.oldx) * friction, // vx = dx / dt -> dt = 1: vx = dx
vy = (p.y - p.oldy) * friction;
p.oldx = p.x;
p.oldy = p.y;
p.x += vx;
p.y += vy;
p.y += gravity;
// collision detection
for(let j = 0; j < points.length; j++) {
if ( i !== j ) {
if (Math.abs( p.x - points[j].x ) < 5 && Math.abs( p.y - points[j].y ) < 5) {
vx = ( 0.5*(p.x - p.oldx) + 0.5*(points[j].x - points[j].oldx) ) * friction;
vy = ( 0.5*(p.y - p.oldy) + 0.5*(points[j].y - points[j].oldy) ) * friction;
//p.oldx = p.x;
//p.oldy = p.y;
p.x += vx*0.011;
p.y += vy*0.011;
//p.y += gravity;
points[j].oldx = points[j].x;
points[j].oldy = points[j].y;
points[j].x += vx;
points[j].y += vy;
points[j].y += gravity;
}
}
}
if(p.x > width) {
p.x = width;
p.oldx = p.x + vx * bounce;
}
else if(p.x < 0) {
p.x = 0;
p.oldx = p.x + vx * bounce;
}
if(p.y > height) {
p.y = height;
p.oldy = p.y + vy * bounce;
}
else if(p.y < 0) {
p.y = 0;
p.oldy = p.y + vy * bounce;
}
}
}
function renderPoints() {
context.clearRect(0, 0, width, height);
for(let i = 0; i < points.length; i++) {
let p = points[i];
context.beginPath();
context.arc(p.x, p.y, 5, 0, Math.PI * 2); // draw a small ball
context.fill();
}
}
};
</script>
</html>