Explosion Damage Handling

Hi. I remember seeing a solution to this somewhere in the FPS tutorial, but I can’t seem to find it again.

Basically, my enemy fires a rocket at the player. If the rocket hits the player, it takes 80% of the health away. I have that part down. However, I’m looking to have a handler where the rocket would inflict damage if it detonated NEAR the player, but not directly on him/her.

Does anyone have a script I would add into my rocket controller that determines the distance from the object tagged as “Player” and deals out the damage accordingly? For example (just throwing numbers out there):

5m away = -70
10m away = -40
15m away = -15
20m away = -5

Any help would be greatly appreciated. Thank you!

When the rocket detonates, you need to find the transform of the player.

FindWithTag() can find the player for you. Then, you just need to find its transform. I trust you know how to do this.

You also need to have the transform of your rocket. Presumably you are calling this from inside your rocket, so thats an easy transform.position

Distance between the two is easy to calculate with this: Unity - Scripting API: Vector3.Distance

For convenience, you may want to add a vector3 to your player’s transform.position in order to offset it to its center of mass. This creates more realistic explosion effects for the next part.

If the distance is over a threshold (lets assume 10m), exit with no damage done. Damage is easiest handled by a simple linear decay between the two extremes. I trust you are familiar with the y=mx+b form of a line:

y=( -1/8 )x + 80

Y here is the damage dealt, while x is how far away you are. B is the maximum damage, and M is (-1)*B/thresholdDistance.

Make sure you dont accidentally call this function when you are directly hit by a rocket, or you will take damage twice.

Also, this is a question for Unity Answers, not the forum.

Is there a way to make this exponential?

I’d recommend that you create a new post with your question. This thread is nearly 8 years old.:slight_smile:

Ok, I think I got it anyway.