Archive

I have a “Mortality” behavior that I can attach to any game object that has health and can die. This is pretty generic, so this means it can refer to a player or character, but also to destructible objects in the scene, such as barrels and plants. As I’m still learning best practices for accomplishing specific tasks in Unity, I’d like to share my approach to this behavior. Note that this is a simplified version that you can extend to meet your needs.

The main Mortality.cs script has some variables you would expect: health (int), dead (bool), etc. The key item to note here is the use of delegates and events. By declaring delegate and event combinations (such as OnDeathEvent() and OnDeath), other objects that have this Mortality behavior can register functions to be called when these events occur. The nice thing is that this is a collection, so you can add any number of functions as listeners to these events – not just one. You just have to remember to deregister the functions when the containing object is disabled or destroyed.

For example, let’s say you have a Barrel.cs behavior attached to a destructible barrel game object. If you attach the Mortality.cs script to it above, then you can handle specific health and death events on the barrel like so:

In a previous post, I detailed a methods of using tweens to give explosion debris some bounce and life. I knew at the time that this would be expensive for a large number of particles – but it was the right look and I at least wanted the temporary solution in the game. Consider it a living mockup, waiting to be optimized.

Recently I came across this post on gamasutra by Mohan Rajagopalan describing design philosophies and techniques behind 2D jumps. Sure enough, the parabolic arc equation was exactly what I needed for my debris bounce, which could be considered debris “jumping.” Here’s the classic formula:

The implementation of this as a Unity component is quite straightforward , and here’s a simple version of the Update() function of the behavior:

One thing to note is that I subtract the previously calculated y-offset since I am adding the new y-offset to the current position each update. This allows this parabolic offset to be additive to any other motion the game object is already undergoing. This is perfect in my case, since the debris is being ejected by an explosive force, and I am just adding this to the y-axis to simulate bouncing in overhead 2D space. As stated in the original post, the root of all this is the simple fact that Unity doesn’t allow gravity in the z-axis for 2D projects.