Unity Raycast NinjaFoo way

PHOTO EMBED

Wed Jan 27 2021 14:56:42 GMT+0000 (Coordinated Universal Time)

Saved by @cotterdev #c#

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

public class PlayerRaycaster : MonoBehaviour
{
    #region Init
    //Variables
    [SerializeField] private float _rayCastLength;
    private ContactFilter2D _myFilter;
    private List<RaycastHit2D> _hits = new List<RaycastHit2D>();        //Only used as a parameter


    // Start is called before the first frame update
    void Start()
    {
        //SEtup because the example we saw said so
        _myFilter = new ContactFilter2D
        {
            useTriggers = false,
            useLayerMask = true    //Not needed, only keeping here in case we want to modify further
        };
        _myFilter.SetLayerMask(LayerMask.GetMask("Platform"));    //Sets the raycast to only return hits on the Player
    }
    #endregion


    #region Update - Draw Ray (Debug only)
    // Update is called once per frame
    void Update()
    {        
        float _dir = Mathf.Sign(transform.localScale.x);            //Used to determine direction char is facing, this is used to find x offset as the ray was not directly over player
        
        //Draw ray for debug
        Vector2 _startRayPos = new Vector2(this.transform.position.x + (0.5f * _dir), this.transform.position.y);  //0.5f is x offset      
        Vector2 _endRayPos = new Vector2(0.0f, _rayCastLength);

        Debug.DrawRay(_startRayPos, _endRayPos, Color.red);
        
    }
    #endregion


    #region FixedUpdate Raycast
    void FixedUpdate()
    {
        //Raycast - Look for platform
        float _dir = Mathf.Sign(transform.localScale.x);            //Used to determine direction char is facing, this is used to find x offset as the ray was not directly over player

        //Setup Raycast Vectors
        Vector2 _startRayPos = new Vector2(this.transform.position.x + (0.5f * _dir), this.transform.position.y);  //RayCast Start = 0.5f is x offset
        Vector2 _endRayPos = new Vector2(0.0f, _rayCastLength);

        //Check for hits by launching raycast
        int _raycastReturn = Physics2D.Raycast(_startRayPos, _endRayPos, _myFilter, _hits, _rayCastLength);

        if (_raycastReturn > 0)
        {
            Debug.Log("Raycast hit a platform above us");

            foreach (var item in _hits)
            {
                Debug.Log($"Hit: {item.collider.tag}");
            }            
        }
    }//End FixedUpdate
    #endregion
}//End Class
content_copyCOPY