我是 java 的初学者,正在为这个问题而苦苦挣扎。这是假设射弹的发射点是 (0,0) 并且它会一直保持相同的速度。
现在,这就是我所拥有的:
public static void main( String[] args )
{
// Testing data
System.out.println(calculateShotAngle(5, 0, 1, 0, 2));
System.out.println(calculateShotAngle(0, 5, 0, 1, 2));
System.out.println(calculateShotAngle(0, -5, 0, -1, 2));
System.out.println(calculateShotAngle(5, 5, 1, 1, 2));
System.out.println(calculateShotAngle(5, -5, 1, -1, 2));
System.out.println(calculateShotAngle(-5, 5, -1, 1, 2));
System.out.println(calculateShotAngle(-5, -5, -1, -1, 2));
System.out.println(calculateShotAngle(5, 0, 1, 1, 2));
System.out.println(calculateShotAngle(-5, 0, 0, -1, 2));
System.out.println(calculateShotAngle(0, 5, 1, 0, 2));
}
public static float calculateShotAngle(float xPosition, float yPosition, float xVelocity,
float yVelocity, float projectileSpeed)
{
// Find the distance to the target
float distance = (float) Math.sqrt(Math.pow(xPosition, 2) + Math.pow(yPosition, 2));
// Find the time it takes to reach target
float t = distance / projectileSpeed;
// Find the position of the target when the projectile reaches it
float xTarget = (xPosition + xVelocity * t);
float yTarget = (yPosition + yVelocity * t);
// Calculate the angle
float angle = (float) Math.atan2(yTarget - yPosition, xTarget - xPosition);
return angle;
}
这些是返回的值:
0.0 1.5707964 -1.5707964 0.7853982 -0.7853982 2.3561945 -2.3561945 0.7853982 -1.5707964 0.0
这些是我应该得到的值:
0.00000000 1.57079633 -1.57079633 0.78539816 -0.78539816 2.35619449 0.78539816 0.54041950 -2.60117315 1.03037683
如有任何帮助,我将不胜感激。
你有耦合方程,其解保证命中:
x0 + vx * t = V cos(alpha) t; y0 + vy * t = V sin(alpha) t;
要求解系统,可以将两个方程都提高到 2 的幂并将它们相加。然后,找到 t 和角度。看代码:
public static float calculateShotAngle(float xPosition, float yPosition, float xVelocity,
float yVelocity, float projectileSpeed)
{
float a = xVelocity * xVelocity + yVelocity * yVelocity - projectileSpeed * projectileSpeed;
float b = 2 * (xPosition * xVelocity + yPosition * yVelocity);
float c = xPosition * xPosition + yPosition * yPosition;
float t = solveQuadraticEquation(a, b, c);
float tan = (yPosition + yVelocity * t) / (xPosition + xVelocity * t);
return (float) Math.atan(tan);
}
public static float solveQuadraticEquation(float a, float b, float c) throws ArithmeticException{
float disc = b * b - 4 * a * c;
if(disc < 0){
throw new ArithmeticException("Complex roots!");
}
float root1 = (float)(- b + Math.sqrt(disc)) / (2 * a);
float root2 = (float)(- b - Math.sqrt(disc)) / (2 * a);
return (root1 >= 0) ? root1 : root2;
}