Thursday, August 2, 2007

Animation-like behaviour in Javascript

I came across a website called Super Maryo World :D As you can figure out by its name, its another remake of the infamous Super Mario Bros. What catches my attention is that it's a game, created entirely in Javascript and can be played in the browser!

To satisfy my curiosity, I tried to somewhat try to code the character movements (move left, right and jump). It does requires some pretty tricky algo.

I was trying to move a div around. First I start of by some basic algo, which is:

OnPress Left
    Move Div Left by 10px

OnPress Right
    Move Div Right by 10px

OnPress Shift
    Move Div Up by 10px

Issues:
  • There's a 0.5 second pause after first movement of 10px, when pressing LEFT or RIGHT before the div continuously moving
  • You can only jump and move... by pressing UP, then DIRECTIONs, not by pressing DIRECTIONs first, then UP.
I'm not quite sure what is really the problem, but I do know that pressing keys may cause events to 'bubble' up (events are collected before it triggers). So it doesn't feels 'real'

Hence, inspired by ActionScript's onEnterFrame() method, a more realistic approach would be:

Use timer to create movements and jump 
OnPress Left
    startTimer To call MoveDiv(left)
       When timer expires, calls MoveDiv(left) recursively while pressing LEFT

OnPress Right
    startTimer To call MoveDiv(right)
       When timer expires, calls MoveDiv(right) recursively while pressing RIGHT

OnPress Shift
     startTimer To call MoveDiv(up)
       When timer expires, calls MoveDiv(up) recursively while pressing UP

and also you must put RETURN FALSE onkeypress ENTER key, to avoid unwanted auto-move bugs :D

No comments: