A code to check if there is no ground so enemy change direction

So basically it, this code can be applied on the enemy to check if there is no ground so the enemy flips.

public class EnemyMovement : MonoBehaviour
{
    [SerializeField] private float moveSpeed = 2f;
    [SerializeField] private Vector2 direction;
    [SerializeField] private float groundDistance = .5f;
    
    
    private Rigidbody2D rb;
    private RaycastHit2D wallRaycastHit;
    private RaycastHit2D fallRaycastHit;
    private LayerMask groundLayer;
    private CapsuleCollider2D capsuleCollider;
    private void Awake()
    {
        rb = GetComponent<Rigidbody2D>();
        capsuleCollider = GetComponent<CapsuleCollider2D>();    
    }

    private void Start()
    {
        groundLayer = LayerMask.GetMask("Ground");
        direction = Vector2.right;

    }

    private void Update()
    {
        rb.velocity = direction * moveSpeed;

        CheckIfWall();
        IsGrounded();
        
        if(wallRaycastHit.collider != null || !IsGrounded())
        {
            ChangeDirection(-direction);
            FlipEnemy();
        }
    }

    private void CheckIfWall()
    {
        float extraWide = .15f;
        wallRaycastHit = Physics2D.Raycast(capsuleCollider.bounds.center, direction, capsuleCollider.bounds.extents.x + extraWide, groundLayer);
        Color rayColor;
        if (fallRaycastHit.collider != null)
        {
            rayColor = Color.green;
        }
        else
        {
            rayColor = Color.red;
        }
        Debug.DrawRay(capsuleCollider.bounds.center, direction * (capsuleCollider.bounds.extents.x + extraWide), rayColor);
    }

    private bool IsGrounded()
    {
        float extraHeight = .15f;
        fallRaycastHit = Physics2D.Raycast(capsuleCollider.bounds.center, Vector2.down, capsuleCollider.bounds.extents.y + extraHeight, groundLayer);
        Color rayColor;
        if(fallRaycastHit.collider != null)
        {
            rayColor = Color.green;
        }
        else
        {
            rayColor = Color.red;
        }
        
        Debug.DrawRay(capsuleCollider.bounds.center, Vector2.down * (capsuleCollider.bounds.extents.y + extraHeight), rayColor);


        return fallRaycastHit.collider != null;
    }

    private void ChangeDirection(Vector2 newDirection)
    {
        direction = newDirection;
    }

    private void FlipEnemy()
    {
        transform.localScale = new Vector2(direction.x, transform.localScale.y);
    }
}

Privacy & Terms