Search code examples
javascriptanimationgeometrygame-physics

Javascript: Bullet animation follow direct path


I'm working on a JS game. At some point a character's bullet needs to travel and hit a target from any angle. Ive tried something like this in the game loop:

if (bx < targetX-speed) bx += speed;
if (bx > targetX+speed) bx -= speed;
if (by < targetY-speed) by += speed;
if (by > targetY+speed) by -= speed;

Obviously it can only travel at 0 and 45 degree angles and that just looks horrible.

I thought of bringing geometry into play by calculating the angle before the bullet fires as such:

angle = Math.atan((by-targetY)/(bx-targetX));

Knowing the angle I can probably calculate either bx or by increasing one parameter i.e.:

by += speed;
bx = by*Math.tan(angle);

The only problem is that I cant do both at once. And I wouldn't be able to use the same for all angles.

Does anyone have a better solution?

Thanks in advance <3 Walt


Solution

  • You've got the solution (though personally I'd use sin instead of tan because tan is discontinuous). The only thing is you're confusing the coordinate system.

    The solution is:

    angle = Math.atan((shooterY-targetY)/(shooterX-targetX));
    

    Calculate that only once when the bullet is fired then store that angle in a variable. Then you can do:

    by += speed;
    bx = by*Math.tan(angle);
    

    Additional answer

    My personally preferred solution is:

    var dy = shooterY-targetY;
    var dx = shooterX-targetX;
    var distance = Math.sqrt(dy*dy+dx*dx);
    var angle = Math.asin(dy/distance);
    

    Then calculate dy and dx for the bullet:

    var speed = SOME_SPEED;
    var b_dy = Math.sin(angle) * speed;
    var b_dx = Math.cos(angle) * speed;
    

    Then move the bulled each frame:

    by += b_dy;
    bx += b_dx;