Hey,
My game has a theme of ‘Tower Defense’.
and i have problem with missiles.
I have a code for a regular Bullet, it destroy a target on hit.
Now i wanted to upgrade it and added some sort of explosion to it, it should destroy the targets in a collider radius.
here is the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bullet : MonoBehaviour
{
private Transform target;
public float speed = 70f;
public float explosionRadius = 0f;
public GameObject impactEffect;
public void Seek(Transform _target)
{
target = _target;
}
void Update()
{
if (target == null)
{
Destroy(gameObject);
return;
}
Vector3 dir = target.position - transform.position;
float distanceThisFrame = speed * Time.deltaTime;
if (dir.magnitude <= distanceThisFrame)
{
HitTarget();
return;
}
transform.Translate(dir.normalized * distanceThisFrame, Space.World);
transform.LookAt(target);
}
void HitTarget()
{
GameObject effectIns = (GameObject)Instantiate(impactEffect, transform.position, transform.rotation);
Destroy(effectIns, 5f);
if (explosionRadius > 0f)
{
Explode();
}
else
{
Damage(target);
}
Destroy(gameObject);
}
void Explode()
{
Collider[] colliders = Physics.OverlapSphere(transform.position, explosionRadius);
foreach (Collider collider in colliders)
{
if (collider.tag == "Enemy")
{
Damage(collider.transform);
}
}
}
void Damage (Transform enemy)
{
Destroy(enemy.gameObject);
}
void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, explosionRadius);
}
}
the code for the regular bullet works completly fine, it destroys a target with the tag “Enemy” on hit, but when a explosions radius (explosionRadius = 0f) than nothing happens the missile just dissapear.
i’m confused, did i messed up the void Explode?