Search code examples
javatrigonometryangleprojectile

Can't get bullets to shoot at correct angle?


I've been having some trouble with trying to get a bullet to fire at angle that I put in. I am using eclipse with java.

My code:

x += (int) (spd * Math.cos(dir));
y -= (int) (spd * Math.sin(dir));`

The feel like the reason it's not working is because it is casted to an int which possibly makes it so inaccurate. But in order for it to draw the rectangle it needs ints.

When inputting dir as 0 it's fine and shoots to the right. The problem is when I put in 90, instead of shooting striaght up it shoots off a little to the left.

Any idea on how I can fix this? Thanks!


Solution

  • No, you're making a classic mistake: Java trig functions need radians, not degrees. It's not 90 that you should pass; it's π/2.0.

    So be sure to convert angles in degrees to radians by multiplying by π/180.0.

    This is true for C, C++, Java, JavaScript, C#, and every other language I know. I cannot name a single language that uses degrees for angles.

    double radians = dir*Math.PI/180.0;
    x += (int)(spd*Math.cos(dir));
    y -= (int) (spd * Math.sin(dir));`  // I don't know why you do this.  Funny left-handed coordinate system.
    

    Speed is the magnitude of the velocity vector. The equations, as written, only express velocity as (vx, vy) components.

    If you want displacements, you'll have to multiply by a time step:

    vx = speed*Math.cos(angle);
    vy = speed*Math.sin(angle);
    dx = vx*dt;
    dy = vy*dt;
    x += dx;  // movement in x-direction after dt time w/ constant velocity
    y += dy;  // movement in y-direction after dt time w/ constant velocity
    

    If there's acceleration involved (e.g. gravity), you should calculate the change in velocity over time the same way.