I have some AI characters that I want to aim at the player. I'm trying to implement the equation described here:
http://en.wikipedia.org/wiki/Trajectory_of_a_projectile#Angle_.CE.B8_required_to_hit_coordinate_.28x.2Cy.29
For some reason, it's not working. Here's my function:
private float CalculateShooterAngle(){ Vector2 aimingPosition = targetPosition - playerPosition; float x = aimingPosition.X; float y = -aimingPosition.Y; float v2 = v * v; float v4 = v * v * v * v; float gx2 = g * x * x; float tyv2 = 2 * y * v * v; float gx = g * x; float sq = v4 - (g * (gx2 + tyv2)); if (sq >= 0.0) { float root = (float)Math.Sqrt(sq); float solution1 = (float)Math.Atan((v2 + root) / gx); float solution2 = (float)Math.Atan((v2 - root) / gx); return solution1; }}
Can anyone see what I'm doing wrong? The angle just doesn't work at all. Sometimes it's close, but no cigar. It seems to get worse the further I move the shooter away from the target. In some quadrants, the shooter's direction seems to flip drastically, pointing straight down. I guess some abrupt angle changes are expected, given that I'm arbitrarily choosing solution1, and throwing away solution2. But no matter what solution is chosen, it's just wrong.
One thing I should mention is that the y-axis is flipped from what you might expect. Since it's an XNA-based 2D sprite game, the y axis points downward, much like it would in a 2D image editing program. So, to shoot at an upward angle, the y-component of my velocity would be negative. However, since my gravity is positive, I figured this would even out and that the above equation should probably work no matter what your coordinate system is. Maybe I'm wrong.
If anyone knows of a place where I can host a 23kb Zip file, I would be happy to post a link to my project. It's pretty self contained, and should be easy to build and run if you have XNA installed.
[Edited by - CDProp on July 1, 2010 1:55:27 AM]