Search code examples
javascriptphysicstrigonometrygravityprojectile

How to apply gravity to a projectile that has directional velocity?


I have a bullet that fires at an angle. I want the bullet to react to a gravitational force. The following code is in the update function of a bullet.

this.pos.x += Math.cos(this.angle * Math.PI/4) * (this.vel.x);
this.pos.y += Math.sin(this.angle * Math.PI/4) * (this.vel.y);

This means that the bullet has been fired at this.angle which shouldn't change. The velocities should always be angled at this.angle. The question now is: How do I add gravity? Here is what I've tried so far.

The following code simply curves the bullet (down, but also up).

this.pos.x += Math.cos(this.angle * Math.PI/4) * (this.vel.x);
this.pos.y += Math.sin(this.angle * Math.PI/4) * (this.vel.y);
this.vel.y += GRAVITY

I've also tried this:

this.pos.x += Math.cos(this.angle * Math.PI/4) * (this.vel.x);
this.pos.y += Math.sin(this.angle * Math.PI/4) * (this.vel.y);
this.vel.y += Math.sin(this.angle * Math.PI/4) * GRAVITY

The latter is the closest I've gotten to what I want it to do. However, when this.angle is 0, sin(0) is also 0. This results in strange projectile misbehaviour when the angle is 0.

What are the best / conventional workarounds to this?


Solution

  • Your position equation doesn't depend on the angle. You should only need the angle to initialize the vel.x and vel.y values.

    You should have a normal speed and do initialize them with

    var bulletSpeed = 100;
    this.vel.x = Math.cos(this.angle)*bulletSpeed;
    this.vel.y = Math.sin(this.angle)*bulletSpeed;
    

    Then update the values with

    this.pos.x += this.vel.x;
    this.pos.y += this.vel.y;
    this.vel.y += GRAVITY
    

    This doesn't use gravity as an acceleration though since there's no time variable from what I can tell