- Home /
How to time delay change of physics state via trigger?
So I have rigidbody game objects that fall from a platform and pile up on the floor. Because this pile can get quite large I want to save on physics by switching them to kinematic after they've come to rest on the floor. The problem I have with using 'sleep' is that before the fall the objects need to interact with eachother in a way where they can't sleep too quickly and on the ground new objects keep coming from above and colliding with the objects on the ground so they never have a chance to fall asleep. Obviously I'm trying to find a solution where none of the pieces end up frozen in the air so my concept was to have them pass through a trigger with a time delay that would give them enough time to come to rest and turn off the physics before a new piece lands from above.
Answer by robertbu · Jul 27, 2013 at 09:02 PM
If you know approximately know when they get launched and approximately how long they take to fall, why not avoid the trigger and just put a generous time limit. You could predicate your isKinematic on the object having no velocity. Assuming the timer starts when object is created you can some something like:
function Start() {
InvokeRepeating("Solidify", 3.0, 0.1);
}
function Solidify() {
if (rigidbody.velocity == Vector3.zero) {
rigidbody.isKinematic = true;
CancelInvoke("Solidify");
}
}
So this code waits 3 seconds. Then it tries 10 times a second to make the object kinematic. It only makes it kinematic if the object has no velocity. If you want to use a trigger, you fire of the InvokeRepeating() in OnTriggerEnter().
That's a brilliantly simple solution my friend and I really appreciate it. I'm sticking with the trigger because the platform, while always above the floor, can rise to substantial heights which of course changes the time it take for the object to reach the floor. I've had some issues that require rebuilding the scene so i can't test it immediately but I'll be sure to update this post once I do. Thanks again!