-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path6_rotation_particles.html
113 lines (96 loc) · 2.32 KB
/
6_rotation_particles.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
<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><title>Rotation physics</title></head>
<body>
<canvas id="surface" width="600" height="400"></canvas>
<script>// Version 1: Rotation - X,Y known, need angle
var line = {
x: 300,
y: 200,
length: 50,
angle: 0
};
function Ball(x, y, r) {
this.x = x;
this.y = y;
this.r = r;
this.vx = 0;
this.vy = 0;
Ball.all.push(this);
}
Ball.all = [];
Ball.draw_all = function() {
var i = Ball.all.length;
while (i--) {
Ball.all[i].draw();
}
};
Ball.prototype = {
draw: function() {
ctx.save();
ctx.translate(this.x, this.y);
ctx.fillStyle = "#fb0";
ctx.beginPath();
ctx.arc(0, 0, this.r, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
ctx.restore();
},
remove: function() {
Ball.all.splice(Ball.all.indexOf(this), 1);
}
};
var canvas = document.getElementById("surface");
var ctx = canvas.getContext('2d');
setInterval(function() {
// Clear display
ctx.save();
ctx.fillStyle = "rgba(0, 0, 0, .2)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.restore();
// Update angle - with geometry! =)
line.angle += (Math.PI * 2) / 300;
var x = line.x + line.length * Math.cos(line.angle);
var y = line.y + line.length * Math.sin(line.angle);
// Update balls - with physics! =)
if (Ball.all.length < 200) {
for (var i = 0; i < 5; i++) {
var ball = new Ball(x, y, 2);
var random_offset = Math.random() * 1 - .5;
var speed = Math.random() * 15 + 3;
ball.vx = speed * Math.cos(line.angle + random_offset);
ball.vy = speed * Math.sin(line.angle + random_offset);
}
}
var i = Ball.all.length;
while(i--) {
var ball = Ball.all[i];
ball.x += ball.vx;
ball.y += ball.vy;
ball.vy += .1;
ball.vx *= .999;
ball.vy *= .99;
if (ball.x % canvas.width !== ball.x) {
ball.remove();
}
else if (ball.y >= canvas.height) {
ball.vy = -Math.abs(ball.vy);
ball.vy *= .7;
if (Math.abs(ball.vy) < 1 && Math.abs(ball.vx) < 1) {
ball.remove();
}
}
}
// Draw line
ctx.save();
ctx.strokeStyle = "#fff";
ctx.lineWidth = 3;
ctx.beginPath();
ctx.moveTo(line.x, line.y);
ctx.lineTo(x, y);
ctx.stroke();
ctx.restore();
// Draw balls
Ball.draw_all();
}, 1000 / 77);
</script></body></html>