dontHaveName dontHaveName - 5 months ago 10
HTML Question

Overlapping sprites in HTML canvas

I have found this game, which runs on canvas.

How can they have 2 characters on the same position (in 1 canvas)?

They are probably updating game characters every second like this:

context.clearRect(0, 0, width, height);
for (i=0;i<players.lenght;i++){
context.drawImage(player, player[i][x], player[i][y]);
}


With this code, if 2 players will have same position, 1 player will be invisible..

Is there any better way to draw all the players?

Answer

Just because the players may be in the same game, doesn't mean they see the same view :) (think of any FPS game you've played online)

However, your assumptions are valid. The code I added to your sample code simply adds your player as the last player in the array meaning you will always be show as on top in your game (regardless if there is 2 or 10 players)

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

// Move your player to the top
for (i=0;i<players.lenght;i++){
    if (players.isYou()) {
        var you = players.splice(i, 1);
        players.push(you);
    }
}

for (i=0;i<players.lenght;i++){
    context.drawImage(player, player[i][x], player[i][y]);
}
Comments