Predict the position of a Rigidbody Object in x second

浪尽此生 提交于 2019-11-29 05:17:09

You are even lucky that the value of 1 worked at-all. You shouldn't pass any value above 0.03 to the Physics.Simulate or Physics2D.Simulate function.

When the value is above 0.03, you have to it into pieces then use the Simulate function in a loop. Decrementing the x time while checking if it is still more or equals to Time.fixedDeltaTime should do it.

Replace

Physics.Simulate(timeInSec);

with

while (timeInSec >= Time.fixedDeltaTime)
{
    timeInSec -= Time.fixedDeltaTime;
    Physics.Simulate(Time.fixedDeltaTime);
}

Your new complete predictRigidBodyPosInTime function should look something like this:

Vector3 predictRigidBodyPosInTime(Rigidbody sourceRigidbody, float timeInSec)
{
    //Get current Position
    Vector3 defaultPos = sourceRigidbody.position;

    Debug.Log("Predicting Future Pos from::: x " + defaultPos.x + " y:"
        + defaultPos.y + " z:" + defaultPos.z);

    //Simulate where it will be in x seconds
    while (timeInSec >= Time.fixedDeltaTime)
    {
        timeInSec -= Time.fixedDeltaTime;
        Physics.Simulate(Time.fixedDeltaTime);
    }

    //Get future position
    Vector3 futurePos = sourceRigidbody.position;

    Debug.Log("DONE Predicting Future Pos::: x " + futurePos.x + " y:"
        + futurePos.y + " z:" + futurePos.z);

    //Re-enable Physics AutoSimulation and Reset position
    Physics.autoSimulation = true;
    sourceRigidbody.velocity = Vector3.zero;
    sourceRigidbody.useGravity = false;
    sourceRigidbody.position = defaultPos;

    return futurePos;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!