Gaben
Gaben

Reputation: 1

unity3D, enemy following issue

I'm trying to make enemies follow my player when the player enters the radius area of an enemy, but make the enemy stop following when my bullet hits object or enters radiusArea.

See my gif for more detail:

Gif

script:

using UnityEngine;
using System.Collections;

public class FlyEnemyMove : MonoBehaviour
{
    public float moveSpeed;
    public float playerRange;
    public LayerMask playerLayer;
    public bool playerInRange;

    PlayerController thePlayer;

    // Use this for initialization
    void Start()
    {
        thePlayer = FindObjectOfType<PlayerController>();
    }

    // Update is called once per frame
    void Update()
    {
        flip();
        playerInRange = Physics2D.OverlapCircle(transform.position, playerRange, playerLayer);
        if (playerInRange)
        {
            transform.position = Vector3.MoveTowards(transform.position, thePlayer.transform.position, moveSpeed * Time.deltaTime);

            //Debug.Log(transform.position.y);

        }
        //Debug.Log(playerInRange);
    }

    void OnDrawGizmosSelected()
    {
        Gizmos.DrawWireSphere(transform.position, playerRange);
    }

    void flip()
    {
        if (thePlayer.transform.position.x < transform.position.x)
        {

            transform.localScale = new Vector3(0.2377247f, 0.2377247f, 0.2377247f);
        }
        else
        {

            transform.localScale = new Vector3(-0.2377247f, 0.2377247f, 0.2377247f);
        }
    }
}

I hope someone can help me :(

Upvotes: 0

Views: 115

Answers (1)

Gunnar B.
Gunnar B.

Reputation: 2989

Physics2D.OverlapCircle detects only the collider with the lowest z value (if multiple are in range). So you either need to change the z values so the player has the lowest or you need to work with Physics2D.OverlapCircleAll and check the list to find the player. Or you could change your layers so only the player itself is on that specific layer you feed into the overlap test.

Upvotes: 1

Related Questions