Created
September 9, 2012 07:34
-
-
Save gedex/3683204 to your computer and use it in GitHub Desktop.
Moving element with key control
This file contains hidden or 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> | |
<head> | |
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script> | |
<meta charset=utf-8 /> | |
<title>JS Bin</title> | |
<style> | |
#arena { | |
position: relative; | |
width: 400px; | |
height: 400px; | |
border: 1px solid #333; | |
} | |
#box { | |
position: absolute; | |
left: 0; | |
top: 0; | |
width: 80px; | |
height: 80px; | |
background-color: green; | |
} | |
</style> | |
</head> | |
<body> | |
<div id="arena"> | |
<div id="box"></div> | |
</div> | |
<script> | |
$(function() { | |
var arena = $('#arena'); | |
var box = $('#box'); | |
box.movingLeft = false; | |
box.movingRight = false; | |
box.movingUp = false; | |
box.movingDown = false; | |
var KEY_LEFT = 37, | |
KEY_RIGHT = 39, | |
KEY_UP = 38, | |
KEY_DOWN = 40; | |
var velocity = 25; | |
setInterval(draw, 25); | |
function draw() { | |
var x = parseInt( box.css('left') ); | |
var y = parseInt( box.css('top') ); | |
//console.log('x: ' + x + ', y: ' + y); | |
if ( box.movingLeft ) x -= velocity; | |
else if ( box.movingRight ) x += velocity; | |
if ( box.movingUp ) y -= velocity; | |
else if ( box.movingDown ) y += velocity; | |
// check bounded arena on horizontal axis | |
if ( x <= 0 ) x = 0; | |
if ( x + box.width() > arena.width() ) { | |
x = arena.width() - box.width(); | |
} | |
// check bounded arena on vertical axis | |
if ( y <= 0 ) y = 0; | |
if ( y + box.height() > arena.height() ) { | |
y = arena.height() - box.height(); | |
} | |
// update the position | |
box.css({'left': x}); | |
box.css({'top': y}); | |
} | |
$(document).keydown(onKeyDown); | |
$(document).keyup(onKeyUp); | |
function onKeyDown(e) { | |
if (e.keyCode === KEY_LEFT) box.movingLeft = true; | |
else if (e.keyCode === KEY_RIGHT) box.movingRight = true; | |
if (e.keyCode === KEY_UP) box.movingUp = true; | |
else if (e.keyCode === KEY_DOWN) box.movingDown = true; | |
} | |
function onKeyUp(e) { | |
if (e.keyCode === KEY_LEFT) box.movingLeft = false; | |
else if (e.keyCode === KEY_RIGHT) box.movingRight = false; | |
if (e.keyCode === KEY_UP) box.movingUp = false; | |
else if (e.keyCode === KEY_DOWN) box.movingDown = false; | |
} | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment