Simple 2D AI Chase Script for Unity 3D in C#

Simple game AI can be hard to figure out in Unity 3D without add-ons. Fortunately, you can use a simple C# script to have an enemy chase a player. Make sure your Player object has the “Player” tag set. Then add this script to your enemy object, and set the “Move Speed” and “Rotation” speed to values that work for your game. Make sure you have sprites set for both your player and enemy game objects. Then run the game. Here is the script:

using UnityEngine;

using System.Collections;

 

public class EnemyAI : MonoBehaviour {

public Transform target;

public int moveSpeed;

public int rotationSpeed;

 

private Transform myTransform;

 

// Use this for initialization

void Awake() {

myTransform = transform;

}

 

void Start () {

GameObject go = GameObject.FindGameObjectWithTag(“Player”);

 

target = go.transform;

}

 

// Update is called once per frame

void Update () {

Vector3 dir = target.position – myTransform.position;

dir.z = 0.0f; // Only needed if objects don’t share ‘z’ value

if (dir != Vector3.zero) {

myTransform.rotation = Quaternion.Slerp (myTransform.rotation,

Quaternion.FromToRotation(Vector3.right, dir), rotationSpeed * Time.deltaTime);

}

 

//Move Towards Target

myTransform.position += (target.position – myTransform.position).normalized * moveSpeed * Time.deltaTime;}

}

Let us know how it works for you or if you have a better script, in the comments below!

Original script by penfwasaurus. Updated by robertbu. Compiled, tested and used by Marketing Hackers. Originally published at Unity Answers.

Mont Cessna on LinkedinMont Cessna on Twitter
Mont Cessna
Mont has 10+ years experience in digital marketing. Experienced with LAMP, CMS and HTML5/CSS3 website development, Mont also excels at math and C/C++/C#. He has managed multi-million dollar media buys though Outbrain, Facebook, Taboola, Yahoo Native, Google AdWords and a number of other display advertising vendors. Mont's written work has regularly appeared on the first page of Google News results and the homepage of Yahoo! He has a B.Sc. in Business Administration with a concentration in Marketing from Drexel University.