Last Good Quote: Son's are the seasoning on our lives. - Someone on Facebook

Thursday, July 3

Dominating Keyboard Controll in Javascript

A great blogger at Lost Garden, setup a development challenge. The challenge was to build a game incorporating shadows.

While not exactly in line with his rules, I wrote a javascript game. While building this I had to figure out how to move a character around the screen using javascript.

For those who just like to look at code, here is the source and a demo.

I started by placing a div tag which had absolute positioning. This allowed me to move the div around the screen.

<div id="unit"
top:0px; left:0px;
margin:0px;padding:0px;"><img src=man.gif width=30 height=30></div>

The next step was to capture any key presses for that div, there are a number of ways to do this but I did it with the following javascript:

controlledObj = document.getElementById("unit");
document.onkeydown = keypressed;

The first line let's me know which div I am controlling, the second line captures all key events to the keypressed function.

The key pressed function watches for arrow keys and moves the controlledObject in the appropriate direction:
function keypressed(event)
if(event.type == 'keydown' && event.keyCode == 38)
pos = findPosOfObject(controlledObj);[1]-5;

if(event.type == 'keydown' && event.keyCode == 40)
pos = findPosOfObject(controlledObj);[1]+5;

if(event.type == 'keydown' && event.keyCode == 37)
pos = findPosOfObject(controlledObj);[0]-5;

if(event.type == 'keydown' && event.keyCode == 39)
pos = findPosOfObject(controlledObj);[0]+5;


There is a special function, findPosOfObject(), used in that bit of code, that gives me the precise location of a div tag. This is something I googled, I'm not sure where it came from but it's a pretty simple piece of code. It looks at an object, goes up the DOM tree to find all its parents and finds the exact top and left of the object. It then returns those values in an array.

function findPosOfObject(obj)
var curleft = curtop = 0;
if (obj.offsetParent)
curleft = obj.offsetLeft
curtop = obj.offsetTop
while (obj = obj.offsetParent)
curleft += obj.offsetLeft
curtop += obj.offsetTop

return [curleft,curtop];

And that is how I moved an object around on the screen.

You can see the end results Shrooms
and the code can be downloaded here.



Post a Comment