Code excerpt 1: Friction

Problem: Unity’s stock physics isn’t very good for simulating rolling balls when it comes to friction. Either a) The ball slides around instead of rolling; Or b) The ball retains no momentum whatsoever.

My solution was to disable Unity’s friction entirely, and just calculate it myself. As an added bonus, it makes it much easier to do braking, which ended up being a critical piece of the game. As the ball is a sphere, and is the only physics driven object in the game, I was able to calculate friction as a single particle, and then independently calculate torque.

The code:

With the exception of some miscellaneous initialization, all of the code for this relies on the OnCollisionStay and FixedUpdate callbacks.

What we’re trying to do with OnCollisionStay here is to iterate through all the different contacts and isolate the one with the most ‘up’ normal. Secondarily, the code that determines if the ball has been crushed also resides here. Notably, OnCollisionStay is called once for every collider that the ball’s collider is in contact with, so assume that always could be the case. Since we’re narrowing it down to a single point, we don’t suddenly get much more friction if we touch the edge of the track.

Since WordPress’ code formatting sucks, here’s a link to the code excerpt.