- Home /
How can I make the enemy AI attack the player?
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!
Answer by Llama_w_2Ls · Apr 06, 2021 at 12:02 PM
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:
void Update()
{
//...
if (PlayerIsNear)
{
transform.position = Vector3.MoveTowards(transform.position, Player.position, MovementSpeed);
}
}
Finally, to make the zombie look at the player, you can just use transform.LookAt(Player);
Hope that helps @finn248582
Your answer
Follow this Question
Related Questions
how to make 2D platformer AI for a skeleton 0 Answers
Enemy AI problems 2 Answers
Another function for activating a different script 0 Answers
how to kill an emeny? 1 Answer
Super Sonic Movement Help 1 Answer