Skip to content Skip to sidebar Skip to footer

Making Canvas Sprites Centered On Coordinates

I am working on a Canvas Game on HTML5 Canvas with Vanilla JS. For some reason I am noticing that when I set the player sprite to be drawn in at on the x-axis at x=0, the player ap

Solution 1:

General purpose sprite rendering

I render sprites with the following function.

// assumes ctx is scoped and is the rendering 2d contextfunctiondrawSprite(img, x, y, scale, rotate, alpha){
    var w = img.width;
    var h = img.height;
    ctx.setTransform(scale, 0, 0 ,scale, x, y);
    ctx.rotate(rotate);
    ctx.globalAlpha = alpha;
    ctx.drawImage(img, 0, 0, w, h, -w/2,-h/2, w, h);
}

It draws the sprite with its center at x,y. It is scaled and and rotated and its alpha is set. On a average laptop and on firefox it can do 2000+ sprites in realtime. On chrome its about 1000+

To set the center point use

// assumes ctx is scoped and is the rendering 2d contextfunctiondrawSpriteCenter(img, x, y, cx, cy, scale, rotate, alpha){
    var w = img.width;
    var h = img.height;
    ctx.setTransform(scale, 0, 0 ,scale, x, y);
    ctx.rotate(rotate);
    ctx.globalAlpha = alpha;
    ctx.drawImage(img, 0, 0, w, h, -cx,-cy, w, h);
}

where cx, and cy s the center point of the sprite. (the point around which it rotates)

To draw a sprite with a center cx,cy at x,y and a scale for x and y, rotated with alpha.

// assumes ctx is scoped and is the rendering 2d contextfunctiondrawSpriteFull(img, x, y, cx, cy, scaleX, scaleY, rotate, alpha){
    var w = img.width;
    var h = img.height;
    ctx.setTransform(scaleX, 0, 0 ,scaleY, x, y);
    ctx.rotate(rotate);
    ctx.globalAlpha = alpha;
    ctx.drawImage(img, 0, 0, w, h, -cx, -cy, w, h);
}

The functions modify the current transform and alpha. To reset the canvas state once you are done rendering the sprites you can use

function resetCtx(){
    ctx.setTransform(1, 0, 0, 1, 0, 0);
    ctx.globalAlpha = 1;
}

Solution 2:

You should be able to correct the player's position like @Bangkokian pointed out. Simply wrap that in a function like so:

functionpositionPlayer(x, y) {
    player.pos = [x -= (player.w / 2), y];
}

or even make that a method of the players object.

The collision detection could be solved similarly by altering the 'checkCollision' function to something like:

var checkCollision = function(rect1, rect2) {
    // debugger// centersvar rect1CenteredPos = [rect1.pos[0] - (rect1.w / 2), rect1.pos[1] - (rect1.h / 2)];
    var rect2CenteredPos = [rect2.pos[0] - (rect2.w / 2), rect2.pos[1] - (rect2.h / 2)];

     // console.log(bulletsArray.length);if (rect1CenteredPos[0] < rect2CenteredPos[0] + rect2.w &&
         rect1CenteredPos[0] + rect1.w > rect2CenteredPos[0] &&
         rect1CenteredPos[1] < rect2CenteredPos[1] + rect2.h &&
         rect1.h + rect1CenteredPos[1] > rect2CenteredPos[1]) {
         returntrue;
     }
     returnfalse;
}

Post a Comment for "Making Canvas Sprites Centered On Coordinates"