Reputation: 25
I've used something like this for movement in 2d projects before and it's always worked. I'm using it right now and its giving me the correct angles for some outputs, and the wrong angles. I think there is just some error in my trig that I've gotten wrong. I've checked it about a million times though. Prolly just auto correcting the error in my head. Here is some example output, and the evil codes.
this(x,y): (500.0, 250.0)
dest(x,y): (400.0, 300.0)
DeltX: 100.0
DeltY: -50.0
Angle: 0.46364760900080615 //about 26.56°, should be 206.56° (26.56+pi) i think
XVELOC: 0.08944272
YVELOC: 0.04472136
public void Update(long deltaTime){
if(this.destination == null){
return;
}
this.x += this.x_velocity * deltaTime;
this.y += this.y_velocity * deltaTime;
if(Math.abs(this.x-destination.x) < 1 && Math.abs(this.y-destination.y) < 1){
destination.arrive(this);
}
}
public void setPath(){
if(this.destination == null){
return;
}
double delta_x = (double) (this.x-this.destination.x);
double delta_y = (double) (this.y-this.destination.y);
int sign_x = (int)Math.signum(delta_x);
int sign_y = (int)Math.signum(delta_y);
double radian_angle = Math.atan((delta_x/delta_y));
if(sign_x > 0 && sign_y > 0)
radian_angle += Math.PI;
else if(sign_x > 0 && sign_y < 0)
radian_angle += Math.PI/2;
else if(sign_x < 0 && sign_y > 0)
radian_angle += 3*Math.PI/2;
System.out.println("DeltX: "+delta_x);
System.out.println("DeltY: "+delta_y);
System.out.println("Angle: "+radian_angle);
this.x_velocity = this.max_velocity*(float)Math.cos(radian_angle);
this.y_velocity = this.max_velocity*(float)Math.sin(radian_angle);
System.out.println("XVELOC: "+x_velocity);
System.out.println("YVELOC: "+y_velocity);
}
Upvotes: 2
Views: 1435
Reputation: 82559
Try using atan2
- it's made to handle this for you
double delta_x = (double) (this.x-this.destination.x);
double delta_y = (double) (this.y-this.destination.y);
double radian_angle = Math.atan2(delta_y,delta_x); // arguements are y,x not x,y
http://download.oracle.com/javase/6/docs/api/java/lang/Math.html#atan2%28double,%20double%29
Upvotes: 1