Frage

Random owls appear in my game, which works with 1 owl image:

 owl.x = 54 + (Math.random() * (canvas.width - 64)); //from var reset function
        owl.y = 54 + (Math.random() * (canvas.height - 64));

How to render owl sprite from several images (sprite sheet) with random coordinates for context.clearRect and drawImage?

var owl = {
    x: 0, 
    y: 0,
    width: 54,
    height: 54,
    frames: 2,
    currentFrame: 0,
};

//from render function:

if (owlReady) {

    context.clearRect(0, 0, width, height); 

    context.drawImage(owlImage, owl.x, owl.y * currentFrame, width, height, width, height); 

if (currentFrame == frames) {
    currentFrame = 0;
    } 
else {
    currentFrame++;
    }
}         
    setInterval(render, 550);
War es hilfreich?

Lösung

Here's annotated code that plays a sprite (flapping bird) and also move the sprite across the canvas.

A Demo: http://jsfiddle.net/m1erickson/beudK/

The key to doing 2 animations at once (flap and move) is to maintain 2 timers.

The flap changes to the next image on the spritesheet every 50ms.

// calculate the elapsed times since the last flap

var elapsedFlap=currentTime-lastFlap;

// if 50ms have elapsed, advance to the next image in this sprite

if(elapsedFlap>50){

    // advance to next sprite on the spritesheet (flap)

    bird.currentFrame++;

    // clamp bird.currentFrame between 0-3  (0,1,2,3)
    // (because there are 4 images that make up the whole bird sprite)

    if(bird.currentFrame>bird.frames-1){
        bird.currentFrame=0;
    }

    // reset the flap timer

    lastFlap=time;
}

The sprite moves from left to right across the canvas an moves every 100ms

// calculate the elapsed times since the last move

var elapsedMove=time-lastMove;

// if 100ms have elapsed, move the bird across the canvas

if(elapsedMove>100){
    bird.x+=3;
    lastMove=time;
}

After the current sprite image and the position of the sprite on the canvas have been calculated, then use .drawImage to clip the desired sprite from the spritesheet an draw it at the desired position on the canvas:

// clear the whole canvas

ctx.clearRect(0,0,canvas.width,canvas.height);

// draw the current part of the bird sprite at the current bird.x

ctx.drawImage(spritesheet,
    sx,sy,bird.width,bird.height,       // clip the desired sprite off the spritesheet
    bird.x,bird.y,bird.width,bird.height // draw to the desired position on the canvas
);
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top