Hi, this is my first attempt at an AoE script.
I attached the following to my rockets to do damage and apply an explosion force effect to the enemy it hits and any other enemies within a certain radius:
using UnityEngine;
using System.Collections;
public class RocketExplosion : MonoBehaviour {
public float expRadius = 10f; // Radius within which enemies are damaged.
public float expForce = 100f; // Force that enemies are thrown from the blast.
public GameObject soundPrefab; // Audioclip of explosion.
public GameObject explosionPrefab; // Prefab of explosion effect.
public float Damage=100;
void Start ()
{
}
void OnTriggerEnter2D(Collider2D other){
if(other.gameObject.tag == "Enemy"){
// Find all the colliders on the Enemies layer within the expRadius.
Collider2D[] enemies = Physics2D.OverlapCircleAll (transform.position, expRadius, 1 << LayerMask.NameToLayer("EnemyLayer"));
// For each collider...
foreach(Collider2D en in enemies)
{
// Check if it has a rigidbody (since there is only one per enemy, on the parent).
Rigidbody2D rb = en.GetComponent<Rigidbody2D>();
if(rb != null && rb.tag == "Enemy")
{
// Find the Enemy script and apply damage.
rb.gameObject.GetComponent<HealthEnemy>();
HealthEnemy hp=(HealthEnemy)transform.GetComponent("HealthEnemy");
if(hp){
if(hp.CurrentHealth<=hp.MaxHealth){
hp.CurrentHealth=hp.CurrentHealth-Damage;
}
}
// Find a vector from the rocket to the enemy.
Vector3 deltaPos = rb.transform.position - transform.position;
// Apply a force in this direction with a magnitude of expForce.
Vector3 force = deltaPos.normalized * expForce;
rb.AddForce(force);
}
}
}
// Instantiate the explosion prefab.
Instantiate(explosionPrefab,transform.position, Quaternion.identity);
// Play the explosion sound effect.
Instantiate(soundPrefab, transform.position,transform.rotation);
}
}
Now the explosion is not going off half the time, and it doesn’t cause damage to the enemies.
The explosion force effect seems to work most of the time though.
What am I doing wrong?