Trigger/Runtime/Box2DColliderTrigger.cs

48 lines
1.5 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using Syntriax.Modules.ToggleState;
2022-11-14 12:15:32 +03:00
using UnityEngine;
namespace Syntriax.Modules.Trigger
{
public class Box2DColliderTrigger : Trigger, IColliderTrigger
{
[SerializeField] private LayerMask colliderMask = 0;
public LayerMask ColliderMask { get => colliderMask; set => colliderMask = value; }
public Action<List<Collider2D>> OnTriggeredCollidersUpdated { get; set; } = null;
private Collider2D[] nonAllocResults = new Collider2D[32];
public List<Collider2D> results = new List<Collider2D>(32);
private int previousTriggerCount = 0;
2022-11-14 14:28:00 +03:00
2022-11-14 12:15:32 +03:00
protected void FixedUpdate()
{
if (!ToggleStateMember.IsToggledNullChecked())
return;
int triggerCount = Physics2D.OverlapBoxNonAlloc(transform.position, transform.localScale, 0, nonAllocResults, ColliderMask);
if (triggerCount == previousTriggerCount)
return;
previousTriggerCount = triggerCount;
results.Clear();
for (int i = 0; i < triggerCount; i++)
results.Add(nonAllocResults[i]);
IsTrigerred = triggerCount > 0;
OnTriggeredCollidersUpdated?.Invoke(results);
}
2022-11-14 12:15:32 +03:00
#if UNITY_EDITOR
private void OnDrawGizmosSelected()
{
Gizmos.color = IsTrigerred ? Color.green : Color.red;
Gizmos.DrawWireCube(transform.position, transform.lossyScale);
}
#endif
}
}