namespace Zinnia.Tracking.Collision.Active
{
using System;
using UnityEngine;
using UnityEngine.Events;
using Zinnia.Extension;
///
/// Contains a at the point of a collision from the event data of an .
///
public class CollisionPointContainer : MonoBehaviour
{
///
/// Defines the event for the generated collision point .
///
[Serializable]
public class UnityEvent : UnityEvent { }
[Tooltip("Determines whether the collision point parent is the GameObject that contains a CollisionNotifier or to just search for the containing Transform.")]
[SerializeField]
private bool isParentCollisionNotifier;
///
/// Determines whether the collision point parent is the that contains a or to just search for the containing .
///
public bool IsParentCollisionNotifier
{
get
{
return isParentCollisionNotifier;
}
set
{
isParentCollisionNotifier = value;
}
}
///
/// Emitted when the collision point container is created.
///
public UnityEvent PointSet = new UnityEvent();
///
/// Emitted when the collision point container is destroyed.
///
public UnityEvent PointUnset = new UnityEvent();
///
/// The created container.
///
public GameObject Container { get; protected set; }
///
/// Whether is or .
///
public bool IsSet { get; private set; }
///
/// Creates a new container if it doesn't already exist and sets it to be at the point of the collision of the given event data.
///
/// Contains data about the collision.
public virtual void Set(ActiveCollisionConsumer.EventData eventData)
{
if (!this.IsValidState() || IsSet)
{
return;
}
GameObject collisionInitiator = eventData.Publisher?.SourceContainer;
Collider collisionCollider = eventData.CurrentCollision?.ColliderData;
if (collisionInitiator == null || collisionCollider == null)
{
return;
}
GameObject collidingObject = IsParentCollisionNotifier
? collisionCollider.GetComponentInParent().gameObject
: collisionCollider.GetContainingTransform().gameObject;
if (Container == null)
{
Container = new GameObject();
}
Container.name = $"[Zinnia][CollisionPointContainer][{collisionInitiator.name}]";
Container.transform.parent = collidingObject.transform;
Container.transform.position = collisionInitiator.transform.position;
Container.transform.rotation = collisionInitiator.transform.rotation;
Container.transform.localScale = Vector3.one;
Container.SetActive(true);
IsSet = true;
PointSet?.Invoke(Container);
}
///
/// Unsets the created container.
///
public virtual void Unset()
{
if (!IsSet || Container == null)
{
return;
}
if (Container.activeInHierarchy && gameObject.activeInHierarchy)
{
Container.transform.parent = transform;
}
Container.SetActive(false);
IsSet = false;
PointUnset?.Invoke(Container);
}
protected virtual void OnDisable()
{
Unset();
Destroy(Container);
Container = null;
}
}
}