The best way to damage an enemy (js)

I’ve got a game where I shoot a laser at enemy spaceships. Where is the best place for the script that damages the enemy?

I could do an OnCollisionEnter on the laser when it hits an enemy and access the enemies health, decrease it and destroy it if it reaches zero. But surely the bullet shouldn’t be doing this? I could instead call a function on the enemy eg enemy.doDamage(damageAmt) which will figure out what to do when it’s injured.

Or should I do the OnCollisionEnter on the enemy itself, checking for collision with lasers?

As a general principle entities should manage there own health. This tends to make code simpler to maintain as the entity knows what animations, sounds ect to call when damage is taken. This also allows effects to be applied simply, such as armour, invincibility, weakness.

It’s generally easiest to do this with a public damage method. Call the damage method using send message for on the oncollision method of your bullet.

Good thinking. It is much better to call a function on the Enemy class.

In my opinion, the best way to go about this is have an interface called something like IDamageable, that the Enemy would implement. This interface would have the DealDamage method you suggested with damageAmount and damageType parameters were that needed.

The implementation could then differ for different classes. You could consider the Enemy’s armor in his implementation or consider if (IsIndestructible == false) in a world object etc.