Unity3d Enemy Follow Player Ai - How to make Enemy Attack Player in Unity Game Development Tutorial
Table of Contents
Introduction
In this tutorial, we will create an enemy AI that can follow and attack the player in a Unity 3D game. This is an essential skill for game development, especially in action or adventure games. By the end of this guide, you will have a functional enemy that can chase after the player and initiate an attack.
Step 1: Setting Up the Enemy Game Object
-
Create the Enemy Object
- Open Unity and create a new GameObject for the enemy.
- Name it "Enemy" for clarity.
-
Add Components
- Select the "Enemy" GameObject.
- Add a Rigidbody component:
- Set
Use Gravity
to true. - Set
Is Kinematic
to false.
- Set
- Add a Collider component (e.g., Box Collider) to define the enemy's physical boundaries.
-
Create an Enemy Script
- Right-click in the Project pane and create a new C# script named "EnemyAI".
- Attach the script to the "Enemy" GameObject.
Step 2: Implementing Follow Logic
-
Script Setup
- Open the "EnemyAI" script in your preferred code editor.
-
Define Variables
- Add the following variables at the top of the script:
public Transform player; public float speed = 3.0f; public float attackDistance = 2.0f;
- Add the following variables at the top of the script:
-
Finding the Player
- In the
Start
method, find the player object:void Start() { player = GameObject.FindWithTag("Player").transform; }
- In the
-
Movement Logic
- In the
Update
method, add logic for following the player:void Update() { float distance = Vector3.Distance(transform.position, player.position); if (distance > attackDistance) { Vector3 direction = (player.position - transform.position).normalized; transform.position += direction * speed * Time.deltaTime; } // Call Attack method if in range }
- In the
Step 3: Implementing Attack Logic
-
Attack Method
- Add a method to handle attacking the player when in range:
void Attack() { // Attack logic here Debug.Log("Attacking the player!"); }
- Add a method to handle attacking the player when in range:
-
Update Attack Logic in Update Method
- Modify the
Update
method to call theAttack
method when within range:if (distance <= attackDistance) { Attack(); }
- Modify the
Step 4: Testing the Enemy AI
-
Tag the Player
- Ensure that the player GameObject is tagged as "Player" in the Inspector.
-
Play the Game
- Click the Play button in Unity to test.
- Observe the enemy following and attacking the player when within the defined distance.
Conclusion
In this tutorial, you have learned how to create a simple enemy AI that follows and attacks the player in Unity. You set up the enemy GameObject, implemented the follow logic, and added an attack mechanism. As next steps, consider enhancing the enemy's behavior with additional features such as animations, health, or different attack types to make your game more engaging. Happy game developing!