So i'm making this simple game for school where i need to shoot arrows from a bow in a somewhat realistic way, this is the code for shooting the arrows and displaying the bow. For some reason the longer i wait to click the mouse to shoot the further the arrow appears from the bow. I just can't figure out what's wrong.
// Player Vars
var arrows = new Array();
var angles = new Array();
var xBow = 0, yBow = 0;
var loaded = false;
var timeload = 0;
var BowC, BowR;
var xBowW, yBowH;
var shoot = false;
var angleBow;
var vel;
var acel = 0.1;
function drawThatBow(){
angleBow = Math.atan2(yRato-yBow-bow.height/2, xRato-xBow);
ctx.save();
ctx.translate( xBow, yBow + bow.height/2 );
ctx.rotate( angleBow );
ctx.translate( 0, -bow.height/2 );
ctx.drawImage(bow, BowC * xBowW, BowR, xBowW, yBowH, 0, 0, xBowW, yBowH);
ctx.restore();
}
function Play() {
if (mouseIsDown) {
shoot = true;
} else if (mouseIsUp && shoot) {
SpawnArrow();
shoot = false;
}
DrawArrows();
}
function SpawnArrow(){
arrows.push( {x: xBow, y: yBow, imagem: arrow, angle: angleBow, timer: 0} );
}
function DrawArrows() {
vel = 10;
for (var i = 0; i < arrows.length; i++) {
arrows[i].timer++;
ctx.save();
ctx.translate( x, y );
ctx.rotate( arrows[i].angle );
ctx.translate( 0, -arrows[i].height/2 );
ctx.drawImage(arrows[i].imagem, 0, 0);
ctx.restore();
var x = arrows[i].x + vel * Math.cos(-(arrows[i].angle)) * arrows[i].timer;
var y = arrows[i].y + bow.height/2 - vel * Math.sin(-(arrows[i].angle)) * arrows[i].timer + acel / 2 * arrows[i].timer * arrows[i].timer;
if (arrows[i].x > larg || arrows[i].y > alt) {
arrows.splice(arrows[i], 1);
}
}
}
Ok never mind i got it. i had to declare the variables x and y outside the function after that it worked fine i also moved it up a bit:
for (var i = 0; i < arrows.length; i++) {
arrows[i].timer++;
x = arrows[i].x + vel * Math.cos(-(arrows[i].angle)) * arrows[i].timer;
y = arrows[i].y + bow.height/2 - vel * Math.sin(-(arrows[i].angle)) * arrows[i].timer + acel / 2 * arrows[i].timer * arrows[i].timer;
ctx.save();
ctx.translate( x, y );
ctx.rotate( arrows[i].angle );
ctx.translate( 0, -arrows[i].height/2 );
ctx.drawImage(arrows[i].imagem, 0, 0);
ctx.restore();
if (arrows[i].x > larg || arrows[i].y > alt) {
arrows.splice(arrows[i], 1);
}
}