I’m making a zombie game, and I’m wondering how I can make the enemy AI attack the player. I want the attack to be triggered when the player steps within the enemies’ boundaries, and I want the attack to be a melee (hands on) attack, with no projectiles. I want the enemy to run after the player when the player is within reach, and I want the enemy to attack the player when it is close to him or her. Does anyone have C# script that fills these requirement? If you could kindly share it with me (or give me a pointer on how I can make this attack happen), I would be delighted. I wanna get this Alpha out by tomorrow and (as you can see) I am very behind.
Thanks in advance, and I hope you have a great day! Stay safe!
The first thing you’ll need is a trigger that detects whether the player is near the zombie or not. You can simply use Physics.OverlapSphere for this, for example:
public class ZombieAI : MonoBehaviour
{
public bool PlayerIsNear;
public float Radius;
void Update()
{
PlayerIsNear = false;
Collider[] hitColliders = Physics.OverlapSphere(transform.position, Radius);
foreach (var hitCollider in hitColliders)
{
if (hitCollider.gameObject.CompareTag("Player"))
{
PlayerIsNear = true;
}
}
}
}
Then, to make the zombie follow the player, you can use Vector3.MoveTowards, to move toward the player. E.g: