Predict the position of a Rigidbody Object in x second

后端 未结 1 1029
慢半拍i
慢半拍i 2020-12-16 08:30

Let\'s say that you have a Rigidbody Object that moves. Force is added to this Object via Rigidbody.AddForce or Rigidbody.velocity. Th

相关标签:
1条回答
  • 2020-12-16 09:02

    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;
    }
    
    0 讨论(0)
提交回复
热议问题