Follow Enemy AIHow to make enemies follow a player object in Unity

Author Waldo
Published July 15, 2019

In this video I show you how to create enemy AI that follows your player around the screen.

Video Walkthrough

  • 0:12 - Downloading and importing assets from the asset store
  • 0:30 - Animating and creating our characters
  • 1:10 - Creating a C# script for our Follow Enemy AI script
  • 1:40 - Calculating the direction our player is in real time
  • 2:20 - Adding a RigidBody2D to rotate our enemy to face our player
  • 3:20 - Calculating the rotation in degrees to rotate our enemy
  • 4:20 - Moving our enemy to chase the player object
  • 6:00 - Final Product
  • 6:15 - Tutorial Challenge

Source Code for Enemy.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Enemy : MonoBehaviour{
    public Transform player;
    public float moveSpeed = 5f;
    private Rigidbody2D rb;
    private Vector2 movement;

    // Start is called before the first frame update
    void Start(){
        rb = this.GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update(){
        Vector3 direction = player.position - transform.position;
        float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
        rb.rotation = angle;
        direction.Normalize();
        movement = direction;
    }
    private void FixedUpdate() {
        moveCharacter(movement);
    }
    void moveCharacter(Vector2 direction){
        rb.MovePosition((Vector2)transform.position + (direction * moveSpeed * Time.deltaTime));
    }
}

This tutorial is sponsored by this community

In order to stick to our mission of keeping education free, our videos and the content of this website rely on the support of this community. If you have found value in anything we provide, and if you are able to, please consider contributing to our Patreon. If you can’t afford to financially support us, please be sure to like, comment and share our content — it is equally as important.

Join The Community

Discussion

Browse Tutorials About