Enemy AI. How to make the AI chase the player by using the exact same moves as the player. (2D)
I'm making this platformer and I just added a simple enemy AI that follows the player. But I want to add one extra AI, that chase the player just like the evil twin from Celeste.
The AI basically copies everything the player does. So if the player Jump over obstacles using a Dash ability, then the Enemy will just do the exacty the same.
So what i need is to write a script, that somehow watch the player.position and when abilities is activated, then somwhow record and the player movement, and translate it somehow. Then make the AI chase the player with some time delay. SO my idea could be making something similar like "ghost car" in most racing. Store the player's position in some array. BUT i'm not sure...
So if any of you out there knows how to make this? or maybe have some tips? Any help will be much appreciated.
If the "Ghost Car" solution is the right way: Then how would you make an Array, that copy the player's movement and when the player use an ability like dash?
Answer by TjazS · Jan 02, 2021 at 02:26 PM
@Banditmayonnaise one of the ways is probably just adding a list of waypoints, so when the player is lets say 1f from the last waypoint it deletes the waypoint. Another way that came in my mind is to make like some kind of a line renderer, maybe something like that. Heres the line renderer script from the video:
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Linq; using System;
public class lineCreator : MonoBehaviour { private LineRenderer lineRenderer; private List points = new List(); public Action OnNewPathCreated = delegate { };
private void Awake()
{
lineRenderer = GetComponent<LineRenderer>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Mouse0))
{
points.Clear();
}
if (Input.GetKey(KeyCode.Mouse0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo))
{
if (DistanceToLastPoint(hitInfo.point) > 1f)
{
points.Add(hitInfo.point);
lineRenderer.positionCount = points.Count;
lineRenderer.SetPositions(points.ToArray());
}
}
else if (Input.GetKeyUp(KeyCode.Mouse0))
{
OnNewPathCreated(points);
}
}
Debug.Log(points.Count);
}
private float DistanceToLastPoint(Vector3 point)
{
if (!points.Any())
{
return Mathf.Infinity;
}
return Vector3.Distance(points.Last(), point);
}
} maybe try to do a raycast on player and add a mask ground so it doesnt detect the player and btw abaut the Ai script for me it didnt work so i deleted it. If you found a way to make it work pls let me now :D. If you need help just notify me.