forked from supperjet/H5-Animation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspring-collision-2.html
103 lines (84 loc) · 3.31 KB
/
spring-collision-2.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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<canvas id="canvas" width="500" height="500" style="background:#000;"></canvas>
<script src="../js/utils.js"></script>
<script src="../js/ball.js"></script>
<script>
window.onload = function(){
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
balls = [],
numBalls = 10,
spring = 0.03,
bounce = -0.5,
gravity = 0.1;
for(var i=0; i<numBalls; i++){
var ball = new Ball(Math.random()*50 +5, Math.random()*0xffffff);
ball.x = Math.random()*canvas.width;
ball.y = Math.random()*canvas.height;
ball.vx = Math.random()*6 - 3;
ball.vy = Math.random()*6 - 3;
balls.push(ball);
}
//边界检测
function move(ball){
ball.vy += gravity;
ball.x += ball.vx;
ball.y += ball.vy;
if(ball.x + ball.radius > canvas.width){
ball.x = canvas.width - ball.radius;
ball.vx *= bounce;
}
if(ball.x - ball.radius < 0){
ball.x = ball.radius;
ball.vx *= bounce;
}
if(ball.y + ball.radius > canvas.height){
ball.y = canvas.height - ball.radius;
ball.vy *= bounce;
}
if(ball.y - ball.radius < 0){
ball.y = ball.radius;
ball.vy *= bounce;
}
}
//球体间的碰撞检测
function checkCollision(ballA, i){
for(var j=i+1; j<numBalls; j++){
var ballB = balls[j];
var dx = ballB.x - ballA.x,
dy = ballB.y - ballA.y;
var distance = Math.sqrt(dx*dx + dy*dy);
var min_distance = ballA.radius + ballB.radius;
if(distance < min_distance){
var angle = Math.atan(dy, dx);
var targetX = ballA.x + Math.cos(angle)*min_distance;
var targetY = ballA.y + Math.cos(angle)*min_distance;
var ax = (targetX - ballA.x)*spring*0.5;
var ay = (targetY - ballA.y)*spring*0.5;
ballA.vx -= ax;
ballB.vx += ax;
ballA.vy -= ay;
ballB.vy += ay;
}
}
}
function draw(ball){
ball.draw(context);
}
(function drawFrame(){
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
balls.forEach(move);
balls.forEach(checkCollision);
balls.forEach(draw);
}());
}
</script>
</body>
</html>