In one of our most recent builds we found that collisions detection wasn’t working. For those that don’t know, collision detection is exactly what it sounds like. It is code that recognizes when two objects hit each other.
In Cairn we instantiate special effects & projectiles that use colliders to detect whether it has hit a unit. If it hits the unit it does damage, grants a buff, or assigns a penalty. The problem was that even though units were being hit, the collision detection wasn’t triggering. I recorded a video of the issue while to help a few programmers who were helping to fix it better understand the issue.
Past the break I’ve got some the cause and solution to the problem. Hopefully all my headache will help someone solve the issue more quickly in the future.
So what causes this sort of behavior in Unity3D? Sleeping rigid bodies. A RigidBody is used for all kinds of physics simulation in Unity, from falling down, to being blasted out of the way, to detecting collisions. Measuring these forces can be taxing on the system, so Unity will put a RigidBody to sleep if it hasn’t been interacted with or if it has been at rest for some time.
How could this problem sneak by us? Well we don’t use Unity’s physics engine, we move unit’s with our own scripts. There isn’t much use for gravity simulation in a standard RTS. So our Collisions are treated as Triggers. So the objects don’t really smash into each other, they just notify each other that they have Entered, Exited, or are still inside of one another. This all sounds good, but Triggers don’t wake up a sleeping RigidBody.
Well how do you wake up that RigidBody? We fixed it by adding Kinmatic Rigidbodies to the projectiles & special effects of course. We didn’t have a Rigidbody attached to the projectiles or effects originally, because we didn’t want them to be physical. I want a fire storm to flow through the units, not push them out of the way. Yet the sleeping Rigidbody attached to units can only be woken up by collisions that have their own Rigidbody. To make sure the Rigidbody on the effect isn’t solid though we have to make it Kinmatic, so that it doesn’t use any other Physics.
Once the Colliders have their own Rigid Bodies, marked as Kinmatic, they will wake up any sleeping Rigid Bodies that they come into contact with. Then I get to sleep… Which I haven’t been doing much of while trying to fix this error.