java - Can't get bullets to shoot at correct angle? -


i've been having trouble trying bullet fire @ angle put in. using eclipse java.

my code:

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

the feel reason it's not working because casted int possibly makes inaccurate. in order draw rectangle needs ints.

when inputting dir 0 it's fine , shoots right. problem when put in 90, instead of shooting striaght shoots off little left.

any idea on how can fix this? thanks!

no, you're making classic mistake: java trig functions need radians, not degrees. it's not 90 should pass; it's π/2.0.

so sure convert angles in degrees radians multiplying π/180.0.

this true c, c++, java, javascript, c#, , every other language know. cannot name single language uses degrees angles.

double radians = dir*math.pi/180.0; x += (int)(spd*math.cos(dir)); y -= (int) (spd * math.sin(dir));`  // don't know why this.  funny left-handed coordinate system. 

speed magnitude of velocity vector. equations, written, express velocity (vx, vy) components.

if want displacements, you'll have multiply 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), should calculate change in velocity on time same way.


Comments

Popular posts from this blog

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -