Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate angle required to hit coordinate (x,y) from position other than (0,0) with varying elevation

I am attempting to calculate the angle required to fire a projectile in order to hit a specific coordinate.

My projectile is located a random coordinate and my target coordinate at a static coordinate.

I ended up running across the following equation on Wikipedia for calculating the angle required to hit a coordinate at (x,y) from (0,0):

I have made some attempts to understand this and other formula and attempted the following implementation (I am using c# and XNA).

double y = source.Y - target.Y;
double x = Vector2.Distance(source, target);
double v = 1440; //velocity
double g = 25; //gravity
double sqrt = (v*v*v*v) - (g*(g*(x*x) + 2*y*(v*v)));
sqrt = Math.Sqrt(sqrt);
double angleInRadians = Math.Atan(((v*v) + sqrt)/(g*x));

I have also attempted the following, which resulted in an identical angle where the values of v and g remain the same.

double targetX = target.X - source.X;
double targetY = -(target.Y - source.Y);
double r1 = Math.Sqrt((v*v*v*v) - g*(g*(target.X*target.X) + ((2*target.Y)*(v*v))));
double a1 = ((v*v) + r1)/(g*target.X);
angleInRadians = -Math.Atan(a1);
if (targetX < 0)
{
    angleInRadians -= 180/180*Math.PI;
}

My conjecture is that even in my (assumed) attempt to zero out the source coordinate, that I am still not performing the calculation correctly for coordinates with a non (0,0) source and different elevations.

Below is an image that depicts my coordinate system. It is the default for XNA.

like image 377
Timothy Randall Avatar asked Aug 04 '13 21:08

Timothy Randall


1 Answers

Thanks to the help in the comments the solution to find this angle ended up requiring that the positions be translated to a (0,0) based system. For anyone looking for the same scenario the final working solution was:

double x = -(source.x - target.x);
double y = (source.y - target.y);
double v = 1440; //m/s
double g = 25; //m/s
double sqrt = (v*v*v*v) - (g*(g*(x*x) + 2*y*(v*v)));
sqrt = Math.Sqrt(sqrt);
angleInRadians = Math.Atan(((v*v) + sqrt)/(g*x));

Then to convert the radians into a vector that works with XNA, perform the following conversion:

Vector2 angleVector = new Vector2(-(float)Math.Cos(angleInRadians), (float)Math.Sin(angleInRadians));
like image 77
Timothy Randall Avatar answered Oct 04 '22 20:10

Timothy Randall