Skip to content

Instantly share code, notes, and snippets.

@pete-otaqui
Created June 5, 2013 07:57
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 pete-otaqui/5712298 to your computer and use it in GitHub Desktop.
Save pete-otaqui/5712298 to your computer and use it in GitHub Desktop.
Bouncy ball
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
body {
padding: 0;
margin: 0;
}
#world {
width: 550px;
height: 400px;
background-color:#eee;
}
#ball {
left: 200px;
width: 50px;
height: 50px;
border-radius: 50px;
background-color: #000;
position: absolute;
}
</style>
</head>
<body>
<div id="world">
<div id="ball"></div>
</div>
<script>
var world = document.getElementById('world');
var ball = document.getElementById('ball');
var g = 1;
var vy = 0;
var vx = Math.random() * 20 - 10;
var py = ball.offsetTop;
var px = ball.offsetLeft;
var ox, oy;
var moving = true;
function move() {
window.webkitRequestAnimationFrame(move)
if ( !moving ) {
return;
}
vy = vy + g;
py = py + vy;
px = px + vx;
if (py >= 350) {
py = 350;
vy = vy * -0.8;
vx = vx * 0.8;
}
if ( px >= 500 ) {
px = 500;
vx = vx * -0.8;
} else if ( px <= 0 ) {
px = 0;
vx = vx * -0.5;
}
ball.setAttribute('style', 'top:'+py+'px; left:'+px+'px');
}
window.webkitRequestAnimationFrame(move);
ball.addEventListener('mousedown', function() {
moving = false;
}, false);
ball.addEventListener('mouseup', function() {
moving = true;
vx = ball.offsetLeft - ox;
vy = ball.offsetTop - oy;
}, false);
window.addEventListener('mousemove', function(e) {
if ( !moving ) {
ox = ball.offsetLeft;
oy = ball.offsetTop;
ball.setAttribute('style', 'left:'+e.pageX+'px; top:'+e.pageY+'px');
// $(ball).css({
// left: e.pageX + 'px',
// top: e.pageY + 'px',
// });
}
}, false);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment