user2420951
user2420951

Reputation: 1

Shooting at angle towards last position html5 canvas js

I'm trying to make a game where bullets are shot at a target's last location. The bullets should miss the target unless the target is not moving. Each bullet should continuously move in a single direction using the most recently calculated angle.

for (var z=0; z < this.bullets.length; z++){  

var by = enemy1.y - posY;  
var bx = enemy1.x - posX;  
var fangle = Math.atan2 (by, bx);  


velocitiesx[z] = Math.cos(fangle) * 1;  
velocitiesy[z] = Math.sin(fangle) * 1;  


bullets[z].x += velocitiesx[z] ;  
bullets[z].y += velocitiesy[z] ;   
}

Here is my problem: When the target is not moving, the bullets correctly hit the target. However, when the shooter is moving, but the target is still, all of the bullets miss -- but those bullets should all hit the still, non moving target.

I think what is happening is the program keeps calculating the angle for the newest bullet and using that calculated on the older bullets, causing them to change direction. I am not sure how I could make it so that each new bullet follows the most recently calculated angle and keeps moving in that direction.

changed to (still same problem):

function fire(){
counter++;
if (37 in keys && counter >= firerate ) {
var by = enemy1.y - posY;
var bx = enemy1.x - posX;
var fangle = Math.atan2 (by, bx);
velxf = Math.cos(fangle) * 1;
velyf = Math.sin(fangle) * 1;


bullets[bullets.length] = new Box({
  x: posX  ,
  y: posY ,
  width: 4,
  height: 4,
  color: '#7FFF00',
 });
counter = 0;

} }

function movebullets(){
for (var z=0; z < this.bullets.length; z++){
bullets[z].x += velxf ;
bullets[z].y += velyf ; 
}    
}

Upvotes: 0

Views: 504

Answers (1)

user2420951
user2420951

Reputation: 1

calculated angle and velxf and velyf on fire....and made velxf and velyf properties of box as suggested by kokodoko

bullets[bullets.length] = new Box({
  x: posX  ,
  y: posY ,
  width: 4,
  height: 4,
  color: '#7FFF00',
  velxb: velxf,
  velyb: velyf,
});




function movebullets(){
for (var z=0; z < this.bullets.length; z++){

bullets[z].x += bullets[z].velxb ;
bullets[z].y += bullets[z].velyb ; 
}         
}

Upvotes: 0

Related Questions