I have a player rotating by the mouse and want the bullets line up with the player's gun. Right now they simply come from the point of the player and shoot in the direction of mouse. I just need the bullets to line up with the player's gun as he rotates, rather than at a fixed position. Sorry my math is a little rusty and not sure how to achieve this. I've marked the two spots where I know I need to change.
var player = {
x: (canvas.width/2),
y: (canvas.height-60),
vx: 0,
vy: 0,
Bullets: [],
draw: function() {
ctx.save();
ctx.translate(canvas.width/2, canvas.height-60);
ctx.rotate(Math.atan2(mousePos.x-this.x, this.y-mousePos.y));
ctx.drawImage(img, 0, 702, 42, 64, -21, -33, 42, 64);
ctx.restore();
},
shoot: function() {
var angle = Math.atan2(player.x- mousePos.x, player.y - mousePos.y);
this.Bullets.push(Bullet({
radian: angle,
speed: 6,
x: player.x, //<-- Here
y: player.y, //<-- And Here
}));
}
};
function Bullet(I) {
I.active = true;
I.radian = Math.atan2(player.x- mousePos.x, player.y - mousePos.y);
I.xVelocity = -I.speed * Math.sin(I.radian);
I.yVelocity = -I.speed * Math.cos(I.radian);
I.width = 3;
I.height = 3;
I.color = "#000";
I.inBounds = function() {
return I.x >= 0 && I.x <= canvas.width &&
I.y >= 0 && I.y <= canvas.height;
};
I.draw = function() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
};
I.update = function() {
I.x += I.xVelocity;
I.y += I.yVelocity;
I.active = I.active && I.inBounds();
};
return I;
}
I have tried using the following,
x: Math.cos(mousePos.x- player.x),
y: Math.sin(player.y - mousePos.y),
But the bullets only comes from the top left screen (with the mouse click on the bottom right). Would it have to do with the translate that I doing on the player?