[SOLVED] Ghost enemy AI that follows the player by copying the players position
Okay, the plan is simple. My plan is to make a simple AI that record every player.positions, and then follow the player by using those positions. So the AI will always be some steps behind the player. But when the player stops moving the AI should collide with player and then the player dies.
So my problem is when the player has been chased down by the AI, but it always runs out of position before the enemy AI is ever able to touch the player... Clip showing the problem
I used Queue for making a list of position, this was recommended by someone after I tried with List<>.
public Transform player;
public Transform ghostAI;
public bool recording;
public bool playing;
Queue<Vector2> playerPositions;
public bool playerLeftRadius;
void Start()
{
playerPositions = new Queue<Vector2>();
}
// Update is called once per frame
void Update()
{
if (playerLeftRadius == true)
{
StartGhost();
}
Debug.Log(playerPositions.Count);
}
private void FixedUpdate()
{
if (playing == true)
{
PlayGhost();
}
else
{
Record();
}
}
void Record()
{
recording = true;
playerPositions.Enqueue(player.transform.position);
}
void PlayGhost()
{
ghostAI.transform.position = playerPositions.Dequeue();
}
public void StartGhost()
{
playing = true;
}
public void StopGhost()
{
playing = false;
}
private void OnTriggerExit2D(Collider2D other)
{
Debug.Log("Player leaved the zone");
playerLeftRadius = true;
}
How do improve it so it will be able to touch the player? PLEASE any help will be much appreciated
Hmmm...in FixedUpdate you either record the player position OR move the ghost. Shouldn't you do both? Otherwise the moving ghost runs out of places to go since you stop saving them. I also don't think FixedUpdate is right. You move in update, so save spots there also (unless the player moves by Physivs maybe?)