Hello Unity! I am trying to make some simple AI for some of my enemies in my 2D game. How would I create artificial intelligence that makes the object move away from the player when the player gets close. This is a topdown game.
Try making a collider, and make it a trigger. With your game being top down, I would suggest a circle collider. If you haven’t already, give your player a “Player” tag. Write a script to detect your player (using the player tag) and then make the enemy move. I am not sure how to make it move in the exact opposite direction but you could try something like this
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class enemyFlee : MonoBehaviour {
public EnemyAI enemyAI;
void Awake()
{
enemyAI = gameObject.GetComponentInParent<EnemyAI>();
}
void OnTriggerStay2D(Collider2D col)
{
if(col.CompareTag("Player"))
{
//write script for moving enemy away from player here
}
}
}
Now, I copied and edited this from one of my own codes, so it may be missing some stuff or have some extra code in it. Now, with the moving away from the player I was toying with the idea of setting an integer variable called distance and finding the distance from the player the enemy and adding 1 distance until the player is out of the collider’s range. Not 100% sure how to express this in code, but I am sure there are plenty of lovely brains out there that can help you with that. ![]()