Created
June 5, 2013 07:57
-
-
Save pete-otaqui/5712298 to your computer and use it in GitHub Desktop.
Bouncy ball
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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