以下の内容はhttps://baba-s.hatenablog.com/entry/2023/05/31/111619より取得しました。


【Unity】Collider2D が自分自身の Bounds 内に完全に収まっている時に当たり判定のイベントを実行するクラス

ソースコード

using System;
using Kogane;
using UnityEngine;

public sealed class Example : MonoBehaviour
{
    [SerializeField] private Collider2D m_collider2D;

    private bool m_isHit;

    public event Action<Collider2D> OnEnter;
    public event Action<Collider2D> OnExit;

    private void OnTriggerStay2D( Collider2D other )
    {
        var isContains = m_collider2D.bounds.Contains( other.bounds );

        SetState( isContains, other );
    }

    private void OnTriggerExit2D( Collider2D other )
    {
        SetState( false, other );
    }

    private void SetState( bool isHit, Collider2D other )
    {
        if ( m_isHit == isHit ) return;

        var callback = isHit ? OnEnter : OnExit;
        callback?.Invoke( other );

        m_isHit = isHit;
    }
}

public static class BoundsExtensionMethods
{
    public static bool Contains( this Bounds self, Bounds other )
    {
        return self.Contains( other.min ) && self.Contains( other.max );
    }
}

使用例

using UnityEngine;

public sealed class SampleScene : MonoBehaviour
{
    [SerializeField] private Example m_example;

    private void Awake()
    {
        m_example.OnEnter += _ => Debug.Log( "OnEnter" );
        m_example.OnExit  += _ => Debug.Log( "OnExit" );
    }
}



以上の内容はhttps://baba-s.hatenablog.com/entry/2023/05/31/111619より取得しました。
このページはhttp://font.textar.tv/のウェブフォントを使用してます

不具合報告/要望等はこちらへお願いします。
モバイルやる夫Viewer Ver0.14