简体   繁体   中英

Calculate direction and velocity based horizontal and vertical velocity

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.

Solution by Tim Visee :


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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM