-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathverlet0.html
93 lines (81 loc) · 1.64 KB
/
verlet0.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
<!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.9,
gravity = 0.5,
friction = 0.999;
points.push({
x: 100,
y: 100,
oldx: 95,
oldy: 95
});
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;
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>