Daily progress — Damaging the skeleton

So we have a working attack, and we’ve created the interface for implementing damage in our skeleton, so what do we want to happen when our players sword hits the skeleton? Let’s start simple. Let’s remove a hitpoint, and we’ll make a check to see if all hitpoints are gone, and if they are, we’ll destroy the object. But first, let’s start simple:

In the Skeleton code:

So how do we know we hit the skeleton? Let’s go into our attack code:

We know anything that’s damagable will have the IDamagable interface so let’s make that prerequisite for communicating with the other object that’s entered the swords hitbox.

In the Attack code:

We create a variable hit of type IDamagable, and then assign the other components IDamagable to it if it exists.

We do a null check to see if it exists, and if it does, then call the Damage() function. As our friendly skeleton has an IDamagable interface, we know it will have a Damage function that’s called, so let’s see it in action!

Fantastic! Our sword doesn’t have to know who or what its hitting, just that its hitting something with an IDamagable! And notice we didn’t call the skeletons damage() function, we called it through the IDamagable! Hence the ‘interface’ part of the title. We don’t have to access any enemy or item that can be damaged, we just access the interface and virtually ‘press its button’! This is an amazing programming method! I wonder how we can use it for other situations.

Anyway, let’s now be a little more practical and start reducing hitpoints!

Pretty straightforward, we assign the interfaces Health variable to the built in Enemys health, and every time Damage is called, we reduce it by 1, and if Health is less than 0, destroy the game object. Let’s try it out!

WOO HOO! WE HAVE DESTRUCTIBLE ENEMIES!

But there’s a bit of an issue, when the player hits the skeleton, it can hit more than once because each frame is playing combined with Unity checking for hits around 60 frames per second, we’re going to have to write a cooldown system.

We’ll review Interfaces and Abstract classes first and then we’ll get back to it!

cartoonist, game artist, and wanabe gamedev.