- Home /
Detecting Enemies inside Area,Detecting Enemies inside Circle
Hello, im doing my first game and im trying to detect the enemies inside an circle area around my player.
i have two problems right now:
-When a start the game, the circlecollider and player collider is detected as enemies even when i use the compare tag "Enemy"
-My corroutine dont refresh every 2s, and only detect colliders one time when the game start
public class ItemDamage : MonoBehaviour
{
[SerializeField] int damage;
[SerializeField] Collider2D[] objectsInsideArea;
Vector2 radiusOfDamage;
int radius;
public void Start()
{
radiusOfDamage = new Vector2(radius, 0f);
StartCoroutine(DamageEnemy());
}
bool IsEnemy(string tag)
{
for (int i = 0; i < objectsInsideArea.Length; i++)
if (objectsInsideArea[i].gameObject.CompareTag("Enemy"))
{
Debug.Log("object {i} is an Enemy");
return true;
} else
{
Debug.Log("object {i}");
}
return false;
}
IEnumerator DamageEnemy()
{
objectsInsideArea = Physics2D.OverlapAreaAll(Vector2.zero, radiusOfDamage);
foreach (bool IsEnemy in objectsInsideArea)
{
Debug.Log("You damage the enemy");
}
yield return new WaitForSeconds(2);
}
}
Answer by CodeMonkeyYT · Apr 18 at 07:21 PM
For radiusOfDamage you can just store it as a float
If you want circle detection then you should be using Physics2D.OverlapCircleAll(); instead of Physics2D.OverlapAreaAll(); which uses a Rectangular area.
I covered several methods of Finding Targets in this tutorial video https://unitycodemonkey.com/video.php?v=h9oEhVqGptU
For your coroutine, if you want it to run forever every 2 seconds then you need to put a while (true)
inside it otherwise it will only run once.
IEnumerator DamageEnemy()
{
while (true) {
objectsInsideArea = Physics2D.OverlapCircleAll(transform.position, radiusOfDamage);
foreach (bool IsEnemy in objectsInsideArea)
{
Debug.Log("You damage the enemy");
}
yield return new WaitForSeconds(2);
}
}
i didnot realize that Vector2.zero is global and not local on gameobject. Enemies only got detected when they were in origin. Made some changes to code and now is working 100%. Thanks for the reply!!!