- Home /
How to do explosion damage to enemy with multiple collider?
I make a tank game that the tank has multiple collider s in turret and multiple colliders in hull as the armor. When it take a damage, the tank get multiple damage because it has multiple colliders.
I was using overlap sphere to damage multiple enemies but i just wanna make a damage per enemy in explosion radius not multiple damage for multiple enemies in explosion radius.
So, how to do damage to enemies with multiple collider in it?
Answer by SalvoSoftware · Oct 24, 2020 at 10:14 AM
How do you send damage data to other tanks? You should create a class object and assign it to enemy tanks (but I guess there is already), then when the bullet hits something you could make a map with Closest point per Enemy:
Dictionary<Enemy, float> distanceToTanks = new Dictionary<Enemy, float>();
Then, everytime a collider is hit, you look for Enemy's script and you set the distance only if it's less then the current value:
float currentDistance = Vector3.Distance(middle, collider.ClosestPoint(middle));
Enemy enemy = ...
if (!distanceToTanks.ContainsKey(enemy) || currentDistance < distanceToTanks[enemy]){
distanceToTanks[enemy] = currentDistance;
}
At the end you can iterate through the dictionary to apply damage:
foreach (KeyValuePair<Enemy, float> values in distanceToTanks) {
enemy.ApplyDamage(values.Value, ...);
}
Is this also work when the colliders is separate child?
Yes, of course, as long as the class that represents the tank (which I called Enemy) is the same. You could place that component on the root, the other colliders on first level children and do something like this: Enemy enemy = transform.parent.GetComponent();