0
\$\begingroup\$

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?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

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;
    }
}
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Don't hesitate to accept your own answer, it might help people facing the same problem in the future! \$\endgroup\$
    – Sacha
    Commented Jan 27, 2022 at 14:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .