This repository has been archived by the owner on Dec 22, 2021. It is now read-only.
/
06-angle-bounce-rotate.html
75 lines (70 loc) · 2.34 KB
/
06-angle-bounce-rotate.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
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Angle Bounce Rotate</title>
<link rel="stylesheet" href="../include/style.css">
</head>
<body>
<header>
Example from <a href="http://amzn.com/1430236655?tag=html5anim-20"><em>Foundation HTML5 Animation with JavaScript</em></a>
</header>
<canvas id="canvas" width="400" height="400"></canvas>
<aside>Move mouse left or right on canvas element.</aside>
<script src="../include/utils.js"></script>
<script src="./classes/ball.js"></script>
<script src="./classes/line.js"></script>
<script>
window.onload = function () {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
mouse = utils.captureMouse(canvas),
ball = new Ball(),
line = new Line(0, 0, 300, 0),
gravity = 0.2,
bounce = -0.6;
ball.x = 100;
ball.y = 100;
line.x = 50;
line.y = 200;
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
//move line with mouse
line.rotation = ((canvas.width / 2 - mouse.x) * 0.1) * Math.PI / 180;
//normal motion code
ball.vy += gravity;
ball.x += ball.vx;
ball.y += ball.vy;
//get sine and cosine of angle
var cos = Math.cos(line.rotation),
sin = Math.sin(line.rotation),
//get position of ball, relative to line
x1 = ball.x - line.x,
y1 = ball.y - line.y,
//rotate coordinates
y2 = cos * y1 - sin * x1;
//perform bounce with rotated values
if (y2 > -ball.radius) {
//rotate coordinates
var x2 = cos * x1 + sin * y1,
//rotate velocity
vx1 = cos * ball.vx + sin * ball.vy,
vy1 = cos * ball.vy - sin * ball.vx;
y2 = -ball.radius;
vy1 *= bounce;
//rotate everything back
x1 = cos * x2 - sin * y2;
y1 = cos * y2 + sin * x2;
ball.vx = cos * vx1 - sin * vy1;
ball.vy = cos * vy1 + sin * vx1;
ball.x = line.x + x1;
ball.y = line.y + y1;
}
ball.draw(context);
line.draw(context);
}());
};
</script>
</body>
</html>