Home > OS >  When I first coded the enemy it worked, but now it just doesn't move or follow the player
When I first coded the enemy it worked, but now it just doesn't move or follow the player

Time:08-21

When I first made my enemy and his script everything worked fine. Now when I try to get closer to the enemy it doesn't follow me. When I touch him he deals damage to me as he would normally, but still doesn't follow me. My enemy code is below.

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

public class Enemy : Mover
{
    // Experience
    public int xpValue = 1;

    // Logic
    public float triggerLength = 1;
    public float chaseLength = 5;
    private bool chasing;
    private bool collidingWithPlayer;
    private Transform playerTransform;
    private Vector3 startingPosition;

    // Hitbox
    public ContactFilter2D filter;
    private BoxCollider2D hitbox;
    private Collider2D[] hits = new Collider2D[10];

    protected override void Start()
    {
        base.Start();
        playerTransform = GameManager.instance.player.transform;
        startingPosition = transform.position;
        hitbox = transform.GetChild(0).GetComponent<BoxCollider2D>();
    }

    private void FixedUpdate()
    {
        // Is the player in range?
        if (Vector3.Distance(playerTransform.position, startingPosition) < chaseLength)
        {
            if (Vector3.Distance(playerTransform.position, startingPosition) < triggerLength)
                chasing = true;
            
            if (chasing)
            {
                if (!collidingWithPlayer)
                {
                    UpdateMotor((playerTransform.position - transform.position).normalized);
                }
            }
            else
            {
                UpdateMotor(startingPosition - transform.position);
            }
        }
        else
        {
            UpdateMotor(startingPosition - transform.position);
            chasing = false;
        }

        // Check for overlaps
        collidingWithPlayer = false;
        boxCollider.OverlapCollider(filter, hits);
        for (int i = 0; i < hits.Length; i  )
        {
            if (hits[i] == null)
                continue;

            if (hits[i].tag == "Fighter" && hits[i].name == "Player")
            {
                collidingWithPlayer = true;
            }

            // The array is not cleaned up, so we do it ourself
            hits[i] = null;
        }
    }

    protected override void Death()
    {
        Destroy(gameObject);
        GameManager.instance.GrantXp(xpValue);
        GameManager.instance.ShowText(" "   xpValue   " xp", 30, Color.magenta, transform.position, Vector3.up * 40, 1.0f);
    }
}

If you need another script I can post it in the reply. And a really long error pups up. I don't know if it is something to do with the enemy or not. Error: NullReferenceException: Object reference not set to an instance of an object UnityEditor.Graphs.Edge.WakeUp () (at <06397f6908034403aa752a7eb86035b0>:0) UnityEditor.Graphs.Graph.DoWakeUpEdges (System.Collections.Generic.List1[T] inEdges, System.Collections.Generic.List1[T] ok, System.Collections.Generic.List`1[T] error, System.Boolean inEdgesUsedToBeValid) (at <06397f6908034403aa752a7eb86035b0>:0) UnityEditor.Graphs.Graph.WakeUpEdges (System.Boolean clearSlotEdges) (at <06397f6908034403aa752a7eb86035b0>:0) UnityEditor.Graphs.Graph.WakeUp (System.Boolean force) (at <06397f6908034403aa752a7eb86035b0>:0) UnityEditor.Graphs.Graph.WakeUp () (at <06397f6908034403aa752a7eb86035b0>:0) UnityEditor.Graphs.Graph.OnEnable () (at <06397f6908034403aa752a7eb86035b0>:0)

CodePudding user response:

According to Unity's issue tracker website [1] and Unity's forum [2], the error you have is related to Unity itself.

UpdateMotor() method can be the reason why enemy does not chase the player.For instance, methods below take vectors as parameters and I think these vectors are not a unit vector.

UpdateMotor(startingPosition - transform.position);

UpdateMotor(startingPosition - transform.position);

However, method below has a unit vector since ".normalized" is used.

UpdateMotor((playerTransform.position - transform.position).normalized);

Therefore, when conditions for chasing are met, enemy can only move one unit length towards the player, and you may not noticed movement since it is very small.

Furthermore, UpdateMotor() may not exist in your project. You may try to call a method that does not exist. What is the business logic of the UpdateMotor() method? Could you share your UpdateMotor() method?

If you want an alternative solution, I can say that enemy can have a 2D circle collider. The purpose of using this 2D circle collider is going to be the detection of the player. Since your enemy game object has a circle, you can use Unity's OnTriggerEnter2D() method. Here is the manual page [3].

void OnTriggerEnter2D(Collider2D other)
{
        if(other.tag == "Player")
        {
            // here you can write your business logic
            // In our case, it is chasing
            UpdateMotor((playerTransform.position - transform.position).normalized);
        }
}

Furthermore, if you want enemy to move back its starting position when player flee from enemy, you can use Unity's OnTriggerExit2D() method [4].For instance,

void OnTriggerExit2D(Collider2D other)
{
        if(other.tag == "Player")
        {
            // here you can write your business logic
            // Enemy may want to stay here a few seconds 
            new WaitForSeconds(3);
            // and goes back its initial position
            UpdateMotor(startingPosition - transform.position);
        }
}

[1] https://issuetracker.unity3d.com/issues/unityeditor-dot-graphs-dot-edge-dot-wakeup-null-ref-thrown-when-animating-a-camera

[2] https://forum.unity.com/threads/what-is-this-big-error-im-getting.324597/

[3] https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnTriggerEnter2D.html

[4] https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnTriggerExit2D.html

[5] https://docs.unity3d.com/ScriptReference/WaitForSeconds.html

  • Related