1

I'm doing a basic javascript based game from my studies as homework. While the animation going right just fine, when press on the left Key, I don't find to understand how to make the code taking the second row of the image properly that will show like its moving, just as in the right side The image is here: https://i.stack.imgur.com/zSZwB.jpg

Making the char in game move right and left with proper image taken base on the link gave above.

  function Draw(){
    context.clearRect(0,0,canvas.width,canvas.height);
    context.save();
            context.translate(x,0);
            context.drawImage(backgroundImg,0,0,canvas.width,canvas.height); // Backround image.
            context.drawImage(backgroundImg,canvas.width,0,canvas.width,canvas.height); // Backround image.
             x-=10;
        if( x <- canvas.width ){x=0;}
                context.restore();  
        if(Direction==0){ // Right Direction.
            frameNumber++;
        if(frameNumber==8){frameNumber=0};
            xSprite=(frameNumber%8) * frameWidth;
            context.drawImage(char2,xSprite,0,frameWidth,frameHeight,charx,chary,frameWidth,frameHeight); // Char going right.
                        }
        if(Direction==1){ // Left Direction.
            frameNumber--;
            context.drawImage(char2,xSprite*(frameNumber * frameHeight),frameHeight,frameWidth,frameHeight*2,charx,chary,frameWidth,frameHeight*2); // Char going left.
        if(frameNumber==0){frameNumber=8};
                xSprite=(frameNumber * frameWidth)*frameHeight;
            }
        }
Yakir Malka
  • 308
  • 2
  • 11

1 Answers1

1

I've solved the program and it was with managing the direction. With the above code what happened is that the framenumber would go out of the amount of actual frame numbers I have the in the picture so all I did was add this :

if(frameNumber==0) {
  frameNumber=8
};
xSprite=(frameNumber%8) * frameWidth;
context.drawImage(char2,xSprite,***140***,frameWidth,frameHeight,charx,chary,frameWidth,frameHeight);
GhostCat
  • 137,827
  • 25
  • 176
  • 248
Yakir Malka
  • 308
  • 2
  • 11