Creating Sprite (character) Movement with Javascript and jQuery Ver. 1.0

See Digipiph Game Manager, a HTML5 framework to create character based, moveable sprites and much more!

UPDATE: See step 2 (ver. 1.1).

Skip the theory and walk through and learn by example. Click here to see the demo.

NOTICE: This would not be considered a final version. This is just step 1, however, it serves its purpose of moving a sprite around a web page.

For one of my gaming projects I am working on, I need to create a map travel system for a character to move around a stage. This character will need to move when the arrow keys are pressed, continue moving while the arrow keys are press, and look like it is walking. I will have a series of post that documents my work on how to do this.

Establish a Unit of Measure

I decided that for my unit of measure, I will use 32 square pixels. For movement, I want my character to move 32px for each step. If it were to only move 1px per step - it would take FOREVER for the player to get where they were going unless I would execute the "move" script very fast just to travel distance. Basically, I want my "move" script to execute once and move 32px instead of executing 32 times just to make it the same distance. Talk about overhead...

Creating the Character Image


I will be using a sprite image which is basically a collection of images put into a single image. See the sprite image to the left. Notice I have one image for each direction and step.

IMPORTANT! Notice that the sprite image is 96px wide and 128px high? This is important, seeing as I determined 1 unit is 32px. I want my character to fit nicely in the 32 square pixel unit that I have already predetermined, so each character image in my sprite is 32px wide by 32 pixels high. For a total of three images wide by four images high equals 96px wide by 128px high.


Define the Character for the Browser

Now that we have our character sprite created, we need create our character and tell our browser how to read the sprite image so it knows which image to display. The first step is to define your character as a "div" object on your page.

<div id="character"></div>

Now that the character object is placed, it is time to assign our image to the object. We will do this with CSS.

<style type="text/css">
#character {
	  position: absolute;
	  top: 0px;
	  left: 0px;
	  width: 32px;
	  height: 32px;
	  background: url('character.png') no-repeat;

The CSS tells my character to use "absolute" positioning on a page, positioned at the top left corner, 32 square pixels (my determined unit of measure), and to use the character sprite image I made "character.png".

Define the Character's Stances

Now we need to tell our character what image from the character's sprite image (image.png) it will use. I will do this by assigning classes to my character object. These classes will be:

  • front-right - which will tell the character object to face forward with its right foot forward.
  • front-stand - which will use the character facing forward with feet even.
  • front-left - which will tell the character object to face forward with its left foot forward.
  • back-right - which will tell the character object to face backward with its right foot forward.
  • back-stand - which will use the character facing backward with feet even.
  • back-left - which will tell the character object to face backward with its left foot forward.
  • right-right - which will tell the character object to face right with its right foot forward.
  • right-stand - which will use the character facing right with feet even.
  • right-left - which will tell the character object to face right with its left foot forward.
  • left-right - which will tell the character object to face left with its right foot forward.
  • left-stand - which will use the character facing left with feet even.
  • left-left - which will tell the character object to face left with its left foot forward.

Now we need to define the classes in CSS which will tell our character object which image to display. To do this, we need to move our background image position to display the correct image. For the "front-stand" image to display, we need to slide our background image 32px to the left.

<style type="text/css">
  #character.front-right { background-position: 0px 0px; }
  #character.front-stand { background-position: -32px 0px; }
  #character.front-left { background-position: -64px 0px; }
  #character.left-right { background-position: 0px -32px; }
  #character.left-stand { background-position: -32px -32px; }
  #character.left-left { background-position: -64px -32px; }
  #character.right-right { background-position: -64px -64px; }
  #character.right-stand { background-position: -32px -64px; }
  #character.right-left { background-position: -0px -64px; }
  #character.back-right { background-position: 0px -96px; }
  #character.back-stand { background-position: -32px -96px; }
  #character.back-left { background-position: -64px -96px; }

Making the Character Move

With the character all set up, it is time to make him move. Time to set some global variables to be used in all the functions that we will use to process the character's movement.

<script type="text/javascript">
  //Global variables that will be accessed in the functions below.
  var currentKey;          //records the current key pressed
  var TimerWalk;          //timer handle
  var charStep = 2;       //1=1st foot, 2=stand, 3=2nd foot, 4=stand
  var charSpeed = 400; //how fast the character will move

Now that the basic variables are set up, we can start to manipulate the character. When the page loads, let's set the character to a default stance, which will be the "front-stand" class (character facing forward with feet together).

<script type="text/javascript">
  //Once the DOM is ready, set the character to facing forward (default position)
  $(document).ready(function() {
	//add character state class

Now we will set up the KeyDown and KeyUp functions. It is important to use KeyDown opposed to KeyPress as KeyDown recognizes the arrow keys keyCode and KeyPress does not.

<script type="text/javascript">
  //KeyDown Function
  //if there is no currentKey down, execute charWalk
  $(document).keydown(function(e) {
    if (!currentKey) {
      //set the currentKey to the key that is down
      currentKey = e.keyCode;
      //execute character movement function charWalk('direction')
      switch(e.keyCode) {
        case 38: charWalk('up');    break;
        case 39: charWalk('right'); break;
        case 40: charWalk('down');  break;
        case 37: charWalk('left');  break;
  //KeyUp Function
  $(document).keyup(function(e) {
    //don't stop the walk if the player is pushing other buttons
    //only stop the walk if the key that started the walk is released
    if (e.keyCode == currentKey) {
      //set the currentKey to false, this will enable a new key to be pressed
      currentKey = false;
      //clear the walk timer
      //finish the character's movement
      $('#character').stop(true, true);

The animation functions charWalk('direction') and processWalk('direction'). charWalk is the initial function that is fired from the keyDown function. This function sets the "dir" or "direction" variable from language to code. The reason is earlier in the keyDown function we told this process to move the character "up" and "down" - but the CSS does not use "up" or "down" - it uses "front" and "back". We used "up" and "down" for easier readability. After changing the language to code, fire the initial processWalk and then set the TimerWalk variable for continual walking if the key is held down.

<script type="text/javascript">
  //Character Walk Function
  function charWalk(dir) {
    //adjust from lang to code
    if (dir == 'up') dir = 'back';
    if (dir == 'down') dir = 'front';
    //move the character
    //set the interval timer to continually move the character
    TimerWalk = setInterval(function() { processWalk(dir); }, charSpeed);
  //Process Character Walk Function
  function processWalk(dir) {
    //increment the charStep as we will want to use the next stance in the animation
   //if the character is at the end of the animation, go back to the beginning
    if (charStep == 5) charStep = 1;
    //remove the current class
    //add the new class
    switch(charStep) {
      case 1: $('#character').addClass(dir+'-stand'); break;
      case 2: $('#character').addClass(dir+'-right'); break;
      case 3: $('#character').addClass(dir+'-stand'); break;
      case 4: $('#character').addClass(dir+'-left');  break;
    //move the char
    //we will only want to move the character 32px (which is 1 unit) in any direction
    switch(dir) {
        $('#character').animate({top: '+=32'}, charSpeed);
        //don't let the character move any further up if they are already at the top of the screen
        if ($('#character').position().top > 0) {
          $('#character').animate({top: '-=32'}, charSpeed);
      //don't let the character move any further left if they are already at the left side of the screen  
      if ($('#character').position().left > 0) {
          $('#character').animate({left: '-=32'}, charSpeed);
        $('#character').animate({left: '+=32'}, charSpeed);

Click here to see the demo of the above code.


my english is bad. Forgive!!!Have the above article, what is done with the mouse?clicked character to move to any location coordinates ..I wish you good work thank you for your interest.

I need of a code to dynamic creation  of divs into of another div.Could you me help?

Sure, take a look at this and see if it helps:

Hey thanks for the tutorial, this is exactly what I was looking for! You rawk. gonna implement it on my homepage Will defnitely link to this in my 'resources' section.

Okay, firstly I like how the sprite stops at the top and left left without going behind the border. Notice, when you try to walk to the bottom and the right, t will just keep going and goin. What can I do to fix that?

Hey Eraan, I would strongly suggest you look into this HTML5 method compared to this jQuery method. I started out doing this with jQuery, however, there is a much better way. You should check out the Easel JS framework and see the following link for a "game manager" think I built that works with it. All the code is open source so take a look.