简体   繁体   English

根据水平和垂直速度计算方向和速度

[英]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. 我目前正在使用Java开发游戏,我想根据所有游戏对象随附的水平和垂直速度计算方向和方向速度。 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. 注意:当我问这个问题时,由于我在2年级或3年级,所以我对几何/三角学一无所知。

Solution by Tim Visee : 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. 因为可以有多个可以给出相同角度的垂直和水平速度值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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