【Unity】Physics2D の拡張メソッド

DEVELOP, Unity

using UnityEngine;
 
/// <summary>
/// Physics2Dの拡張メソッド
/// </summary>
public static class Physics2DExtentsion
{
    //Rayの表示時間
    private const float RAY_DISPLAY_TIME = 1;
 
    /// <summary>
    /// Rayを飛ばすと同時に画面に線を描画する
    /// </summary>
    public static RaycastHit2D RaycastAndDraw(Vector2 origin, Vector2 direction, float maxDistance, int layerMask,
        float minDepth = Mathf.Infinity, float maxDepth = Mathf.Infinity)
    {
        RaycastHit2D hit = Physics2D.Raycast(origin, direction, maxDistance, layerMask, minDepth, maxDepth);
 
#if UNITY_EDITOR
        //衝突時のRayを画面に表示
        if (hit.collider)
        {
            Debug.DrawRay(origin, hit.point - origin, Color.blue, RAY_DISPLAY_TIME, false);
        }
        //非衝突時のRayを画面に表示
        else
        {
            Debug.DrawRay(origin, direction * maxDistance, Color.green, RAY_DISPLAY_TIME, false);
        }
#endif
 
        return hit;
    }
 
    public static RaycastHit2D[] RaycastAll(Vector2 origin, Vector2 direction, float maxDistance, int layerMask,
        float minDepth = Mathf.Infinity, float maxDepth = Mathf.Infinity)
    {
        RaycastHit2D[] hits = Physics2D.RaycastAll(origin, direction, maxDistance, layerMask, minDepth, maxDepth);
 
#if UNITY_EDITOR
        foreach (var hit in hits)
        {
            if (hit.collider)
            {
                Debug.DrawRay(origin, hit.point - origin, Color.blue, RAY_DISPLAY_TIME, false);
            }
            //非衝突時のRayを画面に表示
            else
            {
                Debug.DrawRay(origin, direction * maxDistance, Color.green, RAY_DISPLAY_TIME, false);
            }
        }
#endif
        return hits;
    }
}

Posted by kazupon