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.