Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

human stripes animation inside canvas

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
like image 239
Sora Avatar asked Oct 21 '22 04:10

Sora


2 Answers

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

like image 91
MightyPork Avatar answered Nov 01 '22 17:11

MightyPork


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);
like image 44
Sergio Avatar answered Nov 01 '22 15:11

Sergio