jskidd3
jskidd3

Reputation: 4783

HTML5 Canvas: Get rect coords after rotation (relative to screen)

update: function(delta) {
    for (var i = 0; i < this.bullets.length; i++) {
        this.bullets[i].velocity = this.bullets[i].speed * delta;
        this.bullets[i].contextX += this.bullets[i].velocity;
    }
},

draw: function(ctx) {
    for (var i = 0; i < this.bullets.length; i++) {
        ctx.save();

        // Move the context to where the player is then make it face the target degree
        ctx.translate(this.bullets[i].startX, this.bullets[i].startY);
        ctx.rotate(this.bullets[i].rotation);

        ctx.fillRect(this.bullets[i].contextX, -5, 10, 10);
        ctx.restore();
    }
}

The code above contains two methods that describe a class that manages the drawing and updating of bullets. The update method moves a bullet along and the draw function then draws it to the screen.

The canvas does the following:

  1. Saves the current canvas context state
  2. Moves the context to where the bullet originated from
  3. Rotates the canvas to the way the bullet was facing when shot
  4. Draw the rectangle
  5. Restore the canvas context to original state

Here is an image I have made that better describes what the canvas context is doing:

enter image description here

So we know the x position of the bullet but this is relative to the context as it's been rotated. What I need to know is the bullet's X and Y properties in relation to the actual screen. Any ideas as to how I can do this?

Upvotes: 1

Views: 713

Answers (1)

markE
markE

Reputation: 105035

You can calculate the untransformed canvas screen position of your rotated bullet like this:

This function uses some trigonometry to get the bullet angle before and after rotation and it uses pythagora's theorm to calculate how far the bullet is from the player.

function bulletXY(playerX,playerY,bulletX,bulletY,rotation){
    var dx=bulletX-playerX;
    var dy=bulletY-playerY;
    var length=Math.sqrt(dx*dx+dy*dy);
    var bulletAngle=Math.atan2(dy,dx);
    var screenX=playerX+length*Math.cos(bulletAngle+rotation);
    var screenY=playerY+length*Math.sin(bulletAngle+rotation);
    return({x:screenX,y:screenY});
}

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

enter image description here

Upvotes: 1

Related Questions