# Projectile isn't reaching my target.

So I’ve taken some code from a unity answers post that aims to fire a projectile in an arc towards target location. Unfortunately/fortunately none of the posters there seem to be having this problem.

``````   private Vector3 BallisticVel(Transform target)
{
var dir = target.transform.position - transform.position;
var height = dir.y; //Calculate height difference.
dir.y = 0;
var dist = dir.magnitude; //Get horizontal distance.
dir.y = dist; //Set elevation to 45 degrees.
dist += height; //Correct for different heights.
var velocity = Mathf.Sqrt(dist + Physics.gravity.magnitude);

return velocity * dir.normalized;
}

// Update is called once per frame
void Update () {
attackSpeed -= Time.deltaTime;

//After x amount of time, apply damage.
if (attackSpeed <= 0)
{
//fire projectile, when it reaches the target then do this other stuff.

GameObject arrowInstance = Instantiate(arrow, transform.position, transform.rotation) as GameObject;
Rigidbody projectile = arrowInstance.GetComponent<Rigidbody>();

projectile.velocity = BallisticVel(enemy.transform);

if (ac.struck == true)
{
Debug.Log("Struck!");
}
else { Debug.Log("Missed!"); }
//CombatAnimation();
attackSpeed = 2.0f;

}

}
``````

While the projectile fires in the right direction, it only makes it about a two units away from the point of instantiation before landing. It’s a ways off.

I didn’t write the BallisticVel code and I have only a basic understanding of how it works (my physics is terrible), so I was wondering if anyone knows what might be the cause?

I was so skeptical that that ballistic math could have worked out so nicely, with only a square root and no other squares or other things that I worked it out (well, not with the height adjustment, but just where the target is at the same height, and I think you made a mistake - the velocity should be sqrt(dist * gravity), not “+”.

As a side note, how elegant that an angle of 45 degrees yields such a simple velocity calculation! Pretty cool.