- Home /

# RigidBody2D projectile to target calculation

Hi, I am using this code to shoot a projectile in order to hit a target on the ground. I am applying an impulse force in the x direction, which is calculated from its height above the target. I am working out the force to add by dividing the x distance by the time it will take to fall due to gravity, but this is not seeming to work:

```
float xDist = flag.position.x - transform.position.x;
float yDist = transform.position.y - flag.position.y;
float xForce = xDist/(Mathf.Sqrt(2*9.81f*yDist)/9.81f);
rigidBody.AddForce((new Vector2(xForce, 0)) * homingForce, ForceMode2D.Impulse);
```

Can anyone help me? Not sure if my calculations are wrong, or whether the physics is rather different than a real life situation. Any help is greatly appreciated, thanks.

**Answer** by hrishihawk
·
Jan 30, 2018 at 06:46 PM

When I was in a similar situation I got it working by implementing the equation from this site. And I'm not sure if it's the best solution but it's working perfectly.What I did was to calculate the initial velocity of the projectile by solving Equations for the Horizontal Motion of a Projectile.With these conditions horizontal direction.

```
1. Horizontal distance,x (xDist in your case)
2. Initial Horizontal Velocity,vix (which is the value we want to solve)
3. Horizontal acceleration,ax (Which is 0 in your situation)
```

And these vertical conditions

```
1. Vertical Distance,y (negative of yDist because the projectile is going downwards)
2. Intial vertical velocity ( which is 0)
3. And vertical acceleration (-9.8)
```

You can solve for time required ,t using

```
x = vix•t + 0.5*ax*t*t
```

Using the value of t solve for vix

```
x = vix•t
```

Now the force to be added on the projectile will be

```
m*vix/t
```

The AddForce() function assumes that the force is applied over the fixed timestep duration set by the Unity engine.
By default, the fixed timestep is set to 0.02 seconds, you can change it if you want in project settings.You get the value for fixed time step in code using **Time.fixedDeltaTime**.Applying these things you final solution for force will be

```
force = m*vix/Time.fixedDeltaTime.
```

Now you can add force to your rigidbody with

```
rb.AddForce((new Vector2(force, 0)), ForceMode.Force);
```

Hope this helped :)

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