HTML and CSS Reference
In-Depth Information
include screen boundaries, house positions, road limits and so on, and it gets two variables,
including the x and y coordinates of where I want the player to move to. In our example, if I
wanted the player to move left, I'd pass to the method their current left position plus 5 pixels. If
I wanted them to move right, I'd pass its current position minus 5 pixels.
If the character “can move,” I return true , and the character keeps moving; or else, I return
false , and the character remains in their current position.
Note that in the moveX() method, I'm also checking the direction in which the user wants to
go, and then I call a method named startMoving() :
if ( dir == 'left' ) {
this . startMoving ( 'left' , 2 );
}
else {
this . startMoving ( 'right' , 3 );
}
You're probably wondering how the walking effect on the character is achieved. You might
have noticed that I'm using CSS sprites. But how do I activate them? It's actually quite simple,
with the help of a jQuery plugin called Spritely . This amazing plugin enables you to animate
10
CSS sprites simply by calling the method on the relevant element and passing it your
properties (such as the number of frames).
Back to our startMoving() method:
startMoving : function ( dir , state ) {
player . addClass ( dir );
player . sprite ({ fps : 9 , no_of_frames : 3 }). spState ( state );
}
I simply add a direction class to the player element (which sets the relevant sprite image), and
then call the sprite() method from Spritely's API.
Because we are dealing with the Web, I figured that being able to move with the keyboard
arrows would not be enough. You always have to think of the user, your client, who might not
have time to hang out in your world. That is why I added both a navigation bar and an option
to “teleport” the character to a given point in the game — again, using the canImove() method
to check whether the player may move to this point.
Search WWH ::




Custom Search