I am trying to make an rpg and I was wondering if there was a way to make Enemies have a range so that if a player were in that range, the enemy would attack them. Please Help me as soon as possible.
-SK
I am trying to make an rpg and I was wondering if there was a way to make Enemies have a range so that if a player were in that range, the enemy would attack them. Please Help me as soon as possible.
-SK
Hi, you can use simple code:
C#
public float range;
public Transform player;
Update()
{
if(Vector3.Distance(player.position, transform.position) <= range)
{
//go to player
}
}
That’s simple solution, then you can use an trigger in player so enemy can attack him when hit trigger sphere.
One of the possibilities is to use sphere or circle trigger collider.
Add child object
Add rigidbody or rigidbody2d
Add circle or sphere collider to it, set isTrigger=True
Add onTrigger events handler to this child
void OnTriggerEnter2D(Collider2D other) {
if(transform.parent && transform.parent.gameObject != other.gameObject)
Debug.Log (transform.parent.gameObject.name + ": I can see " + other.gameObject.name);
}
Spherecast comes to mind. If you do a Vector3.distance you might want to do a raycast to see if the enemy can see your player. So you don’t get detected through walls and doors or whatever.