Getting startangle for projectile

Hey guys,

for my AI to hit the target I need the start angle for the projectile.

I tried to use this formula from wikipedia but I can´t figure out what I do wrong …

Angle theta required to hit coordinate (x,y)

In code I do it like this:

v is the speed I give to the projectile

private Rigidbody rb;

private Vector3 GetProjectileRotationAtStart(Rigidbody rb, float v, Vector3 targetPos)
    float g = rb.mass * Physics.gravity.y;
    float x = Vector3.Distance(transform.position, target.transform.position);
    float y = targetPos.y;

    float v2 = v * v;
    float v4 = v2 * v2;
    float gx = g * x;
    float gx2 = g * x * x;
    float Twoyv2 = 2 * y * v * v;

    float radianAngle = Mathf.Atan((v2 - Mathf.Sqrt(v4 - (g * (gx2 + Twoyv2)))) / gx);
    float degAngle = Mathf.Rad2Deg * radianAngle;

    Vector3 angle = new Vector3(degAngle, 0, 0);
    return angle;

It always returns a too low angle.
I tried to play around with g but didnt realy make that big of a difference.
Making the minus after v2 a plus made it go way too high.

Please help me!

Thanks a lot!!!

The formula for your angle needs a positive gravity, Physics.gravity.y is negative. Also I would change x and y to be the delta between the projectile and target since the formula assumes start position is 0,0.

So the only changes would be:

float g = rb.mass * -Physics.gravity.y;
float x = targetPos.x - transform.position.x;
float y = targetPos.y - transform.position.y;

Also to note: The sign in front of the square root determines when the projectile will pass through the target going up (neg) or falling down (pos).