unity3d Raycast Physics2D Raycast2D


Example

You can use raycasts to check if an ai can walk without falling off the edge of a level.

using UnityEngine;
    
public class Physics2dRaycast: MonoBehaviour 
    {
        public LayerMask LineOfSightMask;
        void FixedUpdate() 
        {
            RaycastHit2D hit = Physics2D.Raycast(raycastRightPart, Vector2.down, 0.6f * heightCharacter, LineOfSightMask);
            if(hit.collider != null)
            {
                //code when the ai can walk
            }
            else
            {
                //code when the ai cannot walk
            }
    }
}

In this example the direction is right. The variable raycastRightPart is the right part of the character, so the raycast will happen at the right part of the character. The distance is 0.6f times the height of the character so the raycast won't give a hit when he hits the ground that is way lower than the ground he is standing on at the moment. Make sure the Layermask is set to ground only, otherwise it will detect other kinds of objects as well.

RaycastHit2D itself is a structure and not a class so hit can't be null; this means you have to check for the collider of a RaycastHit2D variable.