- Home /
The question is answered, right answer was accepted
Physics behave weirdly after timeScale change
So I have this game where the player robot is able to fire a mortar gun (cannon balls). My code for firing mortars is this:
GameObject m = Instantiate(Mortar, turret.transform.position + Vector3.up, Quaternion.identity) as GameObject;
Rigidbody body = m.GetComponent<Rigidbody>();
var direction = (turret.forward + turret.up * 1f) * 500;
body.AddForce(direction);
And this works really well, this results in a cannon ball being fired about 21 meters away. However, I am doing some operations in my game that takes place as fast as possible (about Time.timeScale = 20). When I then set the timeScale back to 1 after completing these operations, the mortar will now fire with much greater force, and the cannon balls will travel over 100 meters with the same code.
It seems that the Physics system somehow hasn't registered that the timeScale is 1 instead of 20, so it will confuse the timings for the physics.
If I switch to another scene and back to the scene, the physics works fine again. Is there anything I can do to make the Physics behave properly when changing timeScales?
Answer by Kiwasi · Aug 07, 2014 at 07:11 PM
Change Time.fixedDeltaTime by the same amount
Thanks.
I don't commonly mess with timeScale and fixedDeltaTime, so while I'm aware of the principles I don't often put them into practice.
I'll try and look at that, but shouldn't Unity handle that for me? I mean, it has changed it from the correct value to some weird value when I went from timeScale = 1 to timeScale = 20, so I would expect it to just go back to the original value when I go back from timeScale = 20 to timeScale = 1.
That did the trick! For some reason, when I went from timeScale = 1 to timeScale = 20, the fixedDeltaTime went from 0.02 to 0.045, but going back from timeScale = 20 to timeScale = 1 did not change the fixedDeltaTime back. Setting it manually to 0.02 solved it. I still think that Unity should handle this both when setting timeScale up and down.
Unity typically doesn't handle this because there are plenty of cases where handling it differently makes sense. I'm actually surprised that unity changed it at all.
Follow this Question
Related Questions
TimeScaling & Rigidbody problem 0 Answers
Slow motion for Physics game 2 Answers
Clothes goes mad with a near-zero time scale? 0 Answers