Unsure why this code for enemy following player doesn't function as expected (Unity)

Viewed 41

Sorry if the answer is extremely obvious, I'm new to programming and this is the first question I've asked on here. I've been following a tutorial on how to make a 2D maze game using Unity and I had no problems up until i tried to implement a simple AI enemy to follow the player. For some reason the enemy travels towards the player for a very short while before getting stuck in the maze walls.

A gif showing what I mean: https://gyazo.com/78b4300c1aaa463db9342d3bddb8d28f

The enemy script:

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

public class EnemyFollow : MonoBehaviour
{
    public float speed;
    private Transform target;
    void Start()
    {
        target = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
    }

    void Update()
    {
        if (MazeGenerator.instance.GetMazeGridCell(Convert.ToInt32(Math.Ceiling(transform.position.x)), Convert.ToInt32(Math.Ceiling(transform.position.y))))
        {
            transform.position = UnityEngine.Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
        }
    }
}

The player script:

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

public class MazeRunner : MonoBehaviour
{
    public float walkSpeed;
    public float rotationSpeed;
    public Transform rotationTransform;
    Vector2 direction = Vector2.zero;
    int targetX = 1;
    int targetY = 1;

    int currentX = 1;
    int currentY = 1;
    float currentAngle;
    float lastAngle;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        bool targetReached = transform.position.x == targetX && transform.position.y == targetY;
        currentX = Mathf.FloorToInt(transform.position.x);
        currentY = Mathf.FloorToInt(transform.position.y);
        direction.x = Input.GetAxisRaw("Horizontal");
        direction.y = Input.GetAxisRaw("Vertical");
        float angle = 0;

        if (direction.x > 0)
        {
            angle = 270;

            if (MazeGenerator.instance.GetMazeGridCell(currentX + 1, currentY) && targetReached)
            {
                targetX = currentX + 1;
                targetY = currentY;
            }
        }
        else if (direction.x < 0)
        {
            angle = 90;

            if (MazeGenerator.instance.GetMazeGridCell(currentX - 1, currentY) && targetReached)
            {
                targetX = currentX - 1;
                targetY = currentY;
            }
        }
        else if (direction.y > 0)
        {
            angle = 0;

            if (MazeGenerator.instance.GetMazeGridCell(currentX, currentY + 1) && targetReached)
            {
                targetX = currentX;
                targetY = currentY + 1;
            }
        }
        else if (direction.y < 0)
        {
            angle = 180;

            if (MazeGenerator.instance.GetMazeGridCell(currentX, currentY - 1) && targetReached)
            {
                targetX = currentX;
                targetY = currentY - 1;
            }
        }
        else
        {
            angle = lastAngle;
        }
        currentAngle = Mathf.LerpAngle(currentAngle, angle, rotationSpeed * Time.deltaTime);
        transform.position = Vector3.MoveTowards(transform.position, new Vector3(targetX, targetY), walkSpeed * Time.deltaTime);
        rotationTransform.eulerAngles = new Vector3(0, 0, currentAngle);
        lastAngle = angle;

    }
}

The maze generator script:

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

public class MazeGenerator : MonoBehaviour
{

    public static MazeGenerator instance;

    public int mazeWidth;
    public int mazeHeight;
    public string mazeSeed;

    public Sprite floorSprite;
    public Sprite roofSprite;
    public Sprite wallSprite;
    public Sprite wallCornerSprite;

    public MazeSprite mazeSpritePrefab;

    System.Random mazeRG;

    Maze maze;

    public Vector3 mazeGoalPosition;

    public delegate void MazeReadyAction();
    public static event MazeReadyAction OnMazeReady;

    void Awake()
    {
        instance = this;
    }

    void Start()
    {
        mazeRG = new System.Random();

        if (mazeWidth % 2 == 0)
            mazeWidth++;

        if (mazeHeight % 2 == 0)
        {
            mazeHeight++;
        }

        maze = new Maze(mazeWidth, mazeHeight, mazeRG);
        maze.Generate();

        mazeGoalPosition = maze.GetGoalPosition();

        DrawMaze();

        if (OnMazeReady != null)
        {
            OnMazeReady();
        }
    }

    void DrawMaze()
    {
        for (int x = 0; x < mazeWidth; x++)
        {
            for (int y = 0; y < mazeHeight; y++)
            {
                Vector3 position = new Vector3(x, y);

                if (maze.Grid[x, y] == true)
                {
                    CreateMazeSprite(position, floorSprite, transform, 0, mazeRG.Next(0, 3) * 90);
                }
                else
                {
                    CreateMazeSprite(position, roofSprite, transform, 0, 0);

                    DrawWalls(x, y);
                }
            }
        }
    }

    void DrawWalls(int x, int y)
    {
        bool top = GetMazeGridCell(x, y + 1);
        bool bottom = GetMazeGridCell(x, y - 1);
        bool right = GetMazeGridCell(x + 1, y);
        bool left = GetMazeGridCell(x - 1, y);

        Vector3 position = new Vector3(x, y);

        if (top)
        {
            CreateMazeSprite(position, wallSprite, transform, 1, 0);
        }

        if (left)
        {
            CreateMazeSprite(position, wallSprite, transform, 1, 90);
        }

        if (bottom)
        {
            CreateMazeSprite(position, wallSprite, transform, 1, 180);
        }

        if (right)
        {
            CreateMazeSprite(position, wallSprite, transform, 1, 270);
        }

        if (!left && !top && x > 0 && y < mazeHeight - 1)
        {
            CreateMazeSprite(position, wallCornerSprite, transform, 2, 0);
        }

        if (!left && !bottom && x > 0 && y > 0)
        {
            CreateMazeSprite(position, wallCornerSprite, transform, 2, 90);
        }

        if (!right && !bottom && x < mazeWidth - 1 && y > 0)
        {
            CreateMazeSprite(position, wallCornerSprite, transform, 2, 180);
        }

        if (!right && !top && x < mazeWidth - 1 && y < mazeHeight - 1)
        {
            CreateMazeSprite(position, wallCornerSprite, transform, 2, 270);
        }
    }

    public bool GetMazeGridCell(int x, int y)
    {
        return maze.GetCell(x, y);
    }

    public List<Vector3> GetRandomFloorPositions(int count)
    {
        List<Vector3> positions = new List<Vector3>();

        for (int i = 0; i < count; i++)
        {
            Vector3 position = Vector3.one;

            do
            {
                int posX = 0;
                int posY = 0;

                while (!GetMazeGridCell(posX, posY))
                {
                    posX = mazeRG.Next(3, mazeWidth);
                    posY = mazeRG.Next(3, mazeHeight);
                }

                position = new Vector3(posX, posY);
            } while (positions.Contains(position));

            positions.Add(position);
        }

        return positions;
    }

    void CreateMazeSprite(Vector3 position, Sprite sprite, Transform parent, int sortingOrder, float rotation)
    {
        MazeSprite mazeSprite = Instantiate(mazeSpritePrefab, position, Quaternion.identity) as MazeSprite;
        mazeSprite.SetSprite(sprite, sortingOrder);
        mazeSprite.transform.SetParent(parent);
        mazeSprite.transform.Rotate(0, 0, rotation);
    }
}

Please let me know if any more aspects of my project or code are needed to help me. Any help is appreciated. Thank you.

0 Answers
Related