- Home /
How to make sure AIs don't go through walls?
I am currently developing a 2D Dungeon Crawler game. I have a simple enemy AI for the dungeon, but when it is in 'Wander' mode, it is able to simply move through walls and into other rooms, even though they both have BoxCollider2D and Rigidbody2D. I am still new to Unity, so I'm not sure how to make sure this happens.
Here is my Inspector for walls:
Here is my inspector for my enemy:
I am also including my AI script in case it helps: using System.Collections; using System.Collections.Generic; using UnityEngine;
public enum EnemyState
{
Wander,
Follow,
Die
};
public class EnemyController : MonoBehaviour
{
GameObject player;
public EnemyState currState = EnemyState.Wander;
public float range;
public float speed;
private bool chooseDir = false;
private bool dead = false;
private Vector3 randomDir;
// Start is called before the first frame update
void Start()
{
player = GameObject.FindGameObjectWithTag("Player");
}
// Update is called once per frame
void Update()
{
switch (currState)
{
case (EnemyState.Wander):
Wander();
break;
case (EnemyState.Follow):
Follow();
break;
case (EnemyState.Die):
break;
}
if(IsPlayerInRange(range) && currState != EnemyState.Die)
{
currState = EnemyState.Follow;
}
else if(!IsPlayerInRange(range) && currState != EnemyState.Die)
{
currState = EnemyState.Wander;
}
}
private bool IsPlayerInRange(float range)
{
return Vector3.Distance(transform.position, player.transform.position) <= range;
}
private IEnumerator ChooseDirection()
{
chooseDir = true;
yield return new WaitForSeconds(Random.Range(2f, 8f));
randomDir = new Vector3(0, 0, Random.Range(0, 360));
Quaternion nextRotation = Quaternion.Euler(randomDir);
transform.rotation = Quaternion.Lerp(transform.rotation, nextRotation, Random.Range(0.5f, 2.5f));
chooseDir = false;
}
void Wander()
{
if (!chooseDir)
{
StartCoroutine(ChooseDirection());
}
transform.position += -transform.right * speed * Time.deltaTime;
if (IsPlayerInRange(range))
{
currState = EnemyState.Follow;
}
}
void Follow()
{
transform.position = Vector2.MoveTowards(transform.position, player.transform.position, speed * Time.deltaTime);
}
public void Death()
{
Destroy(gameObject);
}
}
Have you tried making your enemy ai's nav$$anonymous$$eshAgents? You can bake a floor mesh, which limits what areas they can walk in and define an obstacle avoidance radius, so they stay away from other colliders and other ai's within this range.
Answer by ShySam · Aug 28, 2020 at 11:37 PM
@M3ntalll did you try to check if there is a collision between the wall and AI collision in the collision matrix (the collision plan between different colliders in the project) you can reach it by going to [ Edit > Project Settings > Physics ] then scroll down to each ( Collision Matrix in the bottom) and see if there is any unchecked box . tell me if it worked for you :D