0
votes

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 ; 
}    
}
1
You keep looping through all the bullets to update their angle, but you only have to update their position. The angle should only be calculated when you fire the bulletKokodoko
It still slightly misses the non-moving target. if the shooter is moving upwards, the bullets are too low. if shooter moving downwards, the bullets go too high.user2420951
the bullet needs to know its own velxf and velyf, so you can make that a property of Box({velx, vely})Kokodoko
hey kokodoko thanks for the help that did the trick! I feel like I never would've seen that, makes sense though. will post the relevant change.user2420951

1 Answers

0
votes

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 ; 
}         
}