Had to add a check on the layer Ground

Otherwise my enemy would get mad around a ladder and go back and forth on it.

    private void OnTriggerExit2D(Collider2D collision)
    {
        if (collision.gameObject.layer == LayerMask.NameToLayer("Ground"))
        {
            // Turn around
            transform.localScale = new Vector2(-transform.localScale.x, transform.localScale.y);
        }
    }

I had to do this too, otherwise collisions with the player near the edge of platforms (where the player has been pushed onto the top of a ladder and is mostly on the ladder) would cause the enemy to oscillate in place. This is because the collider was exiting both the player’s collider and the ground collider in the same frame, which means the OnTriggerExit2D function is called twice, making it turn around twice and therefore just flip over and over on the spot.

This can probably be sorted out with collider geometry, but it does seem cleaner to only make the enemies change direction only if their “probe” leaves the ground, rather than the player or the ground.

Privacy & Terms