using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using Input;
namespace Minigames.DivingForPictures.PictureCamera
{
///
/// Attached to the viewfinder UI prefab. Handles tap detection and other viewfinder-specific operations.
///
public class Viewfinder : MonoBehaviour, ITouchInputConsumer
{
[SerializeField]
private Image[] viewfinderImages; // Array of Image components to tint based on proximity
// Events
public event System.Action OnViewfinderTapped;
public event System.Action OnViewfinderHoldStarted;
public event System.Action OnViewfinderHoldEnded;
// State
private bool isActive = true;
private RectTransform _rectTransform;
private CameraViewfinderManager _viewfinderManager;
private void Awake()
{
_rectTransform = GetComponent();
}
///
/// Initializes the viewfinder with a reference to its manager
///
/// Reference to the CameraViewfinderManager
public void Initialize(CameraViewfinderManager manager)
{
_viewfinderManager = manager;
if (_viewfinderManager != null)
{
_viewfinderManager.OnProximityUpdated += UpdateProximityColor;
}
}
private void OnDisable()
{
// Unsubscribe from events when disabled
if (_viewfinderManager != null)
{
_viewfinderManager.OnProximityUpdated -= UpdateProximityColor;
}
}
///
/// Updates the color of all viewfinder images based on proximity value
///
/// Proximity value between 0 and 1 (0=far, 1=close)
private void UpdateProximityColor(float proximity)
{
// Lerp between green (close) and red (far)
Color tintColor = Color.Lerp(Color.red, Color.green, proximity);
// Apply the color to all referenced image components
if (viewfinderImages != null && viewfinderImages.Length > 0)
{
foreach (Image image in viewfinderImages)
{
if (image != null)
{
image.color = tintColor;
}
}
}
}
///
/// Enable or disable input reception
///
public void SetActive(bool active)
{
isActive = active;
}
#region ITouchInputConsumer Implementation
public void SetupInputOverride()
{
InputManager.Instance.RegisterOverrideConsumer(this);
}
public void RemoveInputOverride()
{
InputManager.Instance.UnregisterOverrideConsumer(this);
}
public void OnTap(Vector2 position)
{
if (isActive)
{
// Fire the tap event that PhotoSequenceController will listen to
OnViewfinderTapped?.Invoke();
Debug.Log($"[MDPI] Viewfinder OnTap: {position}");
}
}
public void OnHoldStart(Vector2 position)
{
if (isActive)
{
// Fire the hold start event
OnViewfinderHoldStarted?.Invoke();
Debug.Log($"[MDPI] Viewfinder OnHoldStart: {position}");
}
}
public void OnHoldMove(Vector2 position)
{
// We can use this for any continuous effects during hold if needed in the future
}
public void OnHoldEnd(Vector2 position)
{
if (isActive)
{
// Fire the hold end event
OnViewfinderHoldEnded?.Invoke();
Debug.Log($"[MDPI] Viewfinder OnHoldEnd: {position}");
}
}
#endregion
///
/// Check if a point is within the viewfinder's bounds
///
public bool ContainsPoint(Vector2 screenPoint)
{
return RectTransformUtility.RectangleContainsScreenPoint(_rectTransform, screenPoint);
}
}
}