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.
I spend a lot of money on Facebook advertising for both businesses and other marketing…
I've worked as a digital marketing consultant for dozens of businesses across different industries and…
F5Bot is a free service that emails you when your selected keywords are mentioned on Reddit, Hacker…
Marketing Hackers is a new media and digital marketing consulting company that focuses on growth…
Marketers have often leveraged the internet's large platforms like social media for marketing. Nevertheless, increasing…
In Laymen's terms, Blockchain Technology can be explained as spreadsheets or ledgers which are shared…
Leave a Comment