This site uses strictly necessary cookies. More Information

X- Home /

# 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 ...

https://en.wikipedia.org/wiki/Projectile_motion 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);
Debug.Log(angle);
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!!!

**Answer** by Ymrasu
·
Mar 18, 2019 at 11:06 PM

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).

### Your answer

### Welcome to Unity Answers

The best place to ask and answer questions about development with Unity.

To help users navigate the site we have posted a site navigation guide.

If you are a new user to Unity Answers, check out our FAQ for more information.

Make sure to check out our Knowledge Base for commonly asked Unity questions.

If you are a moderator, see our Moderator Guidelines page.

We are making improvements to UA, see the list of changes.