5

my jsfiddle : http://jsfiddle.net/yKvuK/

as you can see when the human walk the image remain in it's place can i change the code so when i press left the image change it's position and look like it's walking to the left and not just walk in place ?

            function update() {
            canvas.clearRect(0, 0, CanvasWidth, CanvasHeight);
            if (keydown.left) {
                    CurentPos++;
                    if (CurentPos == ImgNumb) {
                        CurentPos = 0;
                    }
            }
        } // end update
4

2 回答 2

2

Try this fiddle:

http://jsfiddle.net/yKvuK/1/

Basically, each time you change the frame, the "left" variable is decremented, so he moves left.

 // I draw the "init" picture at x=250, so he has more space to walk.

 var left = 250;

 function update() {
     canvas.clearRect(0, 0, CanvasWidth, CanvasHeight);
     if (keydown.left) {
         CurentPos++;
         if (CurentPos == ImgNumb) {
             CurentPos = 0;
         }
         left -= 5; // <----
     }
 } // end update

 ...
 ...


 function draw() {
     canvas.drawImage(characterImg, CurentPos * 64, 0, 64, 64, left, 200, 64, 64);
 }

btw, I've never seen /worked with a canvas. Looks like I was just lucky to pick the right variable :P

于 2013-08-01T10:39:26.713 回答
1

This will work: FIDDLE

Use your x variable (instead of adding new) and you will be able to use it on the move-right movement also. Add it in update().

if (keydown.left) {
    CurentPos++;
    x -= 3;  // I used 3 but increase this to move faster
    if (CurentPos == ImgNumb) {
         CurentPos = 0;
    }
}

and

canvas.drawImage(characterImg, CurentPos * 64, 0, 64, 64, 200 + x, 200, 64, 64);
于 2013-08-01T10:44:35.450 回答