In my game I have the math solved for targeting by first setting a velocity then determining the angle to hit a target already...
How would I go about solving it the other way? Determining the angle first then solving the power required to hit a specific point... I found this one formula below. AS3 doesn't have cos2, it only has Math.cos... Should I multiply the result of Math.cos times two or something? Total brain freeze here... Forgot my math. LoL!
"Shooter's position = (x[sub]0[/sub], y[sub]0[/sub])
Target's Position = (x[sub]1[/sub], y[sub]1[/sub])
Shooting angle = ?
Gravity = g
v[sub]0[/sub] = Sqrt( ( ( (x[sub]1[/sub]-x[sub]0[/sub])[sup]2[/sup] * g) * ( (x[sub]1[/sub]-x[sub]0[/sub]) * Tan ? - (y[sub]1[/sub]-y[sub]0[/sub]) ) ) / (2 * Cos[sup]2[/sup] ?) ) "
My conversion that is not working so far...
The first thing I would suggest is looking up "Rifleman's Rule", WikiPedia has a decent overview:
http://en.wikipedia.org/wiki/Rifleman%27s_rule. This gives you an overview of the math behind hitting a target with non-equal height of start and end positions. Here's a snippet which doesn't do exactly what you want, it actually uses a fixed velocity and then calculates the two possible angles but hopefully once you get your head around the above Rifleman's Rule stuff this should give you a good starting point to experiment:
// R = range of entire arc.
// V = initial velocity.
// A = angle (in RADIANS) based on velocity.
// G = gravity constant.
// Ty = target y height
bool Ballistics::SolveAFromVRGTy( const float v, const float r, const float g, const float y, float& a0, float& a1 )
{
const float v2 = v*v;
const float v4 = v2*v2;
const float r2 = r*r;
const float partial = v4 - ( g * ( g*r2 + 2*y*v2 ) );
// If the partial is negative, there is not enough velocity to get to target.
if( partial <= 0.0f )
return false;
const float root = sqrtf( partial );
const float pos = ( v2+root ) / (g*r);
const float neg = ( v2-root ) / (g*r);
a0 = atanf( pos );
a1 = atanf( neg );
return true;
}
Some better definitions of the above. First, given a fixed velocity you can't always solve the equation, hence the bool return. Second, it returns 2 results, the first is the highest arc possible to hit the target and the second is the lowest (most direct) arc possible. The inputs are the desired velocity (V), the distance from the source and target points (i.e. the straight line which the arc will traverse) and the delta y between source and target (i.e. target.y-source.y, or the other way around, forget).
This is all based on the rifleman's rule I mentioned and if you get your head around that, this should be pretty easy to modify as desired to solve for the different variables. If you have problems modifying this let me know, but it should get you started in the correct direction.