Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
74 lines (66 sloc) 2.13 KB
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Angle Bounce</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>
<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'),
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;
line.rotation = 10 * Math.PI / 180; //10 degrees to radians
//get sine and cosine of angle
var cos = Math.cos(line.rotation),
sin = Math.sin(line.rotation);
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
//normal motion code
ball.vy += gravity;
ball.x += ball.vx;
ball.y += ball.vy;
//get position of ball, relative to line
var x1 = ball.x - line.x,
y1 = ball.y - line.y,
//rotate coordinates
x2 = cos * x1 + sin * y1,
y2 = cos * y1 - sin * x1,
//rotate velocity
vx1 = cos * ball.vx + sin * ball.vy,
vy1 = cos * ball.vy - sin * ball.vx;
//perform bounce with rotated values
if (y2 > -ball.radius) {
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>