Reputation: 3248
I'm currently working on a game in Java and I want to calculate the direction and the directional velocity from horizontal and vertical velocity which is supplied with all game objects. I would like to have a method like the one bellow to calculate the direction/angle the object is moving towards (based on it's horizontal and vertical velocity);
public double getAngle() {
// Calculate angle/direction from the horizontal and vertical speed here
return angle;
}
Of course, I'd need a similar method to calculate the directional velocity of an object based on it's horizontal and vertical velocity.
Note: At the time I asked this question I didn't learned anything about geometry/trigonometry because I was in 2nd or 3th class.
Upvotes: 0
Views: 6001
Reputation: 3015
I think
angle = Math.toDegrees(Math.atan2(verticalSpeed,HorizontalSpeed) )
should work
Getting velocity from angle is not possible. Because there can be multiple values of vertical and horizontal speed that can give the same angle.
Upvotes: 5
Reputation: 74530
This is the solution I found after testing some things. I made three functions, the first two could be used to calculate the angle and the velocity from // vertical and horizontal speed. The third function could be used to calculate the horizontal and the vertical velocity from the angle and the velocity.
public static double getAngle(double vx, double vy) {
return Math.toDegrees(Math.atan2(vy, vx));
}
public static double getVelocityWithAngle(double vx, double vy) {
return Math.sqrt(Math.pow(vx, 2) + Math.pow(vy, 2));
}
public static void angleVelocityToXYVelocity(double angle, double velocity) {
double vx = Math.cos(Math.toRadians(angle)) * velocity;
double vy = Math.sqrt(Math.pow(velocity, 2) - Math.pow(vx, 2));
System.out.println("vx: " + vx + " vy: " + vy);
}
Please note that the third function prints the results into the console since it returns two values.
Upvotes: 6