I'm working on a 2D tower defense game using the Unity engine, and so far, everything else works. When it's just one tower, it targets the enemies fine. However, when several towers (even two) are near each other, it does not target them and shoots in the wrong direction.
using UnityEngine;
public class BaseTowerScript : MonoBehaviour
{
public float FireCooldown;
private float FireTimer;
public GameObject TowerBullet;
private Quaternion TargetRotation;
private void Update()
{
if (FireTimer < FireCooldown)
{
FireTimer += 0.0025f;
}
}
private void OnCollisionStay2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Enemy"))
{
TargetRotation = Quaternion.LookRotation((collision.transform.position - transform.position).normalized);
transform.rotation = TargetRotation;
transform.rotation = Quaternion.FromToRotation(Vector3.up, transform.forward);
if (FireTimer >= FireCooldown)
{
GameObject nBullet = Instantiate(TowerBullet, transform.position, transform.rotation);
nBullet.GetComponent<Rigidbody2D>().AddForce(transform.up, ForceMode2D.Impulse);
FireTimer = 0;
}
}
}
}
I tried setting up a layer for towers and having the tower's circle collider ignore that layer so they wouldn't detect each other. I tried switching it to a trigger, but it didn't work. What I would like to have is to have the towers even when near each other to target the enemies. Any suggestions or answers are appreciated.