Skip to content

Instantly share code, notes, and snippets.

@tomnomnom
Created December 27, 2015 20:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomnomnom/311875ddde83d0ec9e1e to your computer and use it in GitHub Desktop.
Save tomnomnom/311875ddde83d0ec9e1e to your computer and use it in GitHub Desktop.
Bouncy Ball
<html>
<head>
<style>
canvas {
border: 1px solid #666666;
}
</style>
</head>
<body>
<canvas id="stage" width="300" height="300">No Canvas Support</canvas>
</body>
<script>
window.onload = function(){
var canvas = document.getElementById('stage');
var c = canvas.getContext('2d');
var world = {};
world.gravity = 9.81;
world.t = 0;
world.lastT = 0;
var ball = {};
ball.y = 10;
ball.x = canvas.width / 2;
ball.radius = 10;
ball.dy = 0;
ball.dx = 0;
ball.resistance = 0.03;
var drawFrame = function(timestamp){
world.t = timestamp - world.lastT;
world.lastT = timestamp;
// Time in seconds
var t = world.t / 1000;
// Hit the bottom?
if ((ball.y + ball.radius) >= canvas.height){
ball.dy = -ball.dy * 0.75;
ball.y = canvas.height - ball.radius;
}
// Hit the top?
if ((ball.y - ball.radius) <= 0){
ball.dy = -ball.dy * 0.75;
ball.y = ball.radius;
}
// Hit the left?
if ((ball.x - ball.radius) <= 0){
ball.dx = -ball.dx * 0.75;
ball.x = ball.radius;
}
// Hit the right?
if ((ball.x + ball.radius) >= canvas.width){
ball.dx = -ball.dx * 0.75;
ball.x = canvas.width - ball.radius;
}
// Apply gravity
ball.dy += t * world.gravity;
// Air resistance
ball.dy *= 1 - ball.resistance;
ball.dx *= 1 - ball.resistance;
// Move the ball
ball.y += ball.dy;
ball.x += ball.dx;
// Clear the screen
c.fillStyle = 'rgba(255, 255, 255, 1)';
c.fillRect(0, 0, canvas.width, canvas.height);
// Draw the ball
c.beginPath();
c.arc(ball.x, ball.y, ball.radius, 0, Math.PI * 2);
c.fillStyle = 'rgba(50, 50, 50, 1)';
c.fill();
window.requestAnimationFrame(drawFrame);
};
window.onkeydown = function(e){
switch (e.keyCode){
case 37:
// Left key
ball.dx = -10;
break;
case 38:
// Up key
ball.dy = -10;
break;
case 39:
// Right key
ball.dx = 10;
break;
case 40:
// Down key
//ball.dy += 10;
break;
}
};
window.requestAnimationFrame(drawFrame);
};
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment