# Calculating time taken for projectile to reach height (y) and position (xz) at that time in 3D space

I am trying to calculate, given a Rigidbody and a float height, at what time will the Rigidbody reach that height. Given my maths career was given up around 20 years ago, I am trying to convert some equations I found to accommodate this. Namely,

$$t=\frac{V_y+\sqrt{V^2_y+2\cdot g \cdot h}}{g}$$

I have the following function:

private void CalculateTimeToHeightAndPosition(Rigidbody rb, float targetHeight, ref float timeToHeight, ref Vector3 positionAtHeight)
{
float ySpeed = rb.velocity.y;

timeToHeight  = (ySpeed + Mathf.Sqrt((ySpeed * ySpeed) + (2 * -Physics.gravity.y * rb.transform.position.y)) / -Physics.gravity.y);

if (!float.IsNaN(timeToHeight))
{
Vector3 v = rb.position + (rb.velocity * timeToHeight);

positionAtHeight = new Vector3(v.x, targetHeight, v.z);
}
else
{
timeToHeight = 0f;
positionAtHeight = Vector3.zero;
}
}


I think the problem is this is not taking into account the targetHeight, and therefore calculates the time to ground, but I don't know how it fits into this equation. Anyone able to help in how to amend the function?

I re-factored the function to (mainly to keep track of the a,b,c variables) and it seems to have done the job. Simply taking the target position away from initial position seems to have been the answer. Rubber ducking at its finest.

private void CalculateTimeToHeightAndPosition(Rigidbody rb, float targetHeight, ref float timeToHeight, ref Vector3 positionAtHeight)
{
float yTargetPos = targetHeight;
float ySpeed = rb.velocity.y;
float a = -Physics.gravity.y;
float b = ySpeed;
float c = rb.position.y - yTargetPos;

timeToHeight = (b + Mathf.Sqrt(Mathf.Pow(b, 2) + (2 * a * c))) / (2 * a);

if (!float.IsNaN(timeToHeight))
{
Vector3 v = rb.position + (rb.velocity * timeToHeight);

positionAtHeight = new Vector3(v.x, catchTargetHeight, v.z);
}
else
{
timeToHeight = 0f;
positionAtHeight = Vector3.zero;
}
}

• Don't hesitate to accept your own answer, it might help people facing the same problem in the future! Commented Jan 27, 2022 at 14:41