461 lines
16 KiB
C#
461 lines
16 KiB
C#
using Input;
|
|
using UnityEngine;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using UnityEngine.Events;
|
|
using System.Threading.Tasks;
|
|
using Core;
|
|
using Core.Lifecycle;
|
|
|
|
namespace Interactions
|
|
{
|
|
public enum CharacterToInteract
|
|
{
|
|
None,
|
|
Trafalgar,
|
|
Pulver,
|
|
Both
|
|
}
|
|
|
|
/// <summary>
|
|
/// Base class for interactable objects that can respond to tap input events.
|
|
/// Subclasses should override OnCharacterArrived() to implement interaction-specific logic.
|
|
/// </summary>
|
|
public class InteractableBase : ManagedBehaviour, ITouchInputConsumer
|
|
{
|
|
[Header("Interaction Settings")]
|
|
public bool isOneTime;
|
|
public float cooldown = -1f;
|
|
public CharacterToInteract characterToInteract = CharacterToInteract.Pulver;
|
|
|
|
[Header("Interaction Events")]
|
|
public UnityEvent<PlayerTouchController, FollowerController> interactionStarted;
|
|
public UnityEvent interactionInterrupted;
|
|
public UnityEvent characterArrived;
|
|
public UnityEvent<bool> interactionComplete;
|
|
|
|
private IInteractingCharacter _interactingCharacter;
|
|
protected FollowerController FollowerController;
|
|
private bool isActive = true;
|
|
|
|
/// <summary>
|
|
/// Gets whether this interactable is currently active (can be clicked)
|
|
/// </summary>
|
|
public bool IsActive => isActive;
|
|
|
|
// Action component system
|
|
private List<InteractionActionBase> _registeredActions = new List<InteractionActionBase>();
|
|
|
|
|
|
/// <summary>
|
|
/// Register an action component with this interactable
|
|
/// </summary>
|
|
public void RegisterAction(InteractionActionBase action)
|
|
{
|
|
if (!_registeredActions.Contains(action))
|
|
{
|
|
_registeredActions.Add(action);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Unregister an action component from this interactable
|
|
/// </summary>
|
|
public void UnregisterAction(InteractionActionBase action)
|
|
{
|
|
_registeredActions.Remove(action);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Dispatch an interaction event to all registered actions and await their completion
|
|
/// </summary>
|
|
private async Task DispatchEventAsync(InteractionEventType eventType, PlayerTouchController playerRef = null)
|
|
{
|
|
// Collect all tasks from actions that want to respond
|
|
List<Task<bool>> tasks = new List<Task<bool>>();
|
|
|
|
foreach (var action in _registeredActions)
|
|
{
|
|
Task<bool> task = action.OnInteractionEvent(eventType, playerRef, FollowerController);
|
|
if (task != null)
|
|
{
|
|
tasks.Add(task);
|
|
}
|
|
}
|
|
|
|
if (tasks.Count > 0)
|
|
{
|
|
// Wait for all tasks to complete
|
|
await Task.WhenAll(tasks);
|
|
}
|
|
// If no tasks were added, the method will complete immediately (no need for await)
|
|
}
|
|
|
|
/// <summary>
|
|
/// Handles tap input. Triggers interaction logic.
|
|
/// Can be overridden for fully custom interaction logic.
|
|
/// </summary>
|
|
public virtual void OnTap(Vector2 worldPosition)
|
|
{
|
|
// 1. High-level validation
|
|
if (!CanBeClicked())
|
|
{
|
|
return; // Silent failure
|
|
}
|
|
|
|
Logging.Debug($"[Interactable] OnTap at {worldPosition} on {gameObject.name}");
|
|
|
|
// Start the interaction process asynchronously
|
|
_ = StartInteractionFlowAsync();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Template method that orchestrates the entire interaction flow.
|
|
/// </summary>
|
|
private async Task StartInteractionFlowAsync()
|
|
{
|
|
// 2. Find characters - get the ACTIVE controller from InputManager
|
|
BasePlayerMovementController playerController = null;
|
|
|
|
if (InputManager.Instance != null)
|
|
{
|
|
// Get the controller that currently has input control
|
|
var activeController = InputManager.Instance.GetActiveController();
|
|
playerController = activeController as BasePlayerMovementController;
|
|
}
|
|
|
|
// Fallback: if InputManager doesn't have an active controller, try to find PlayerTouchController specifically
|
|
if (playerController == null)
|
|
{
|
|
playerController = FindFirstObjectByType<PlayerTouchController>();
|
|
Logging.Warning("[Interactable] No active controller from InputManager, falling back to FindFirstObjectByType<PlayerTouchController>");
|
|
}
|
|
|
|
_interactingCharacter = playerController;
|
|
FollowerController = FindFirstObjectByType<FollowerController>();
|
|
|
|
// For legacy event compatibility, try to get PlayerTouchController reference
|
|
var playerRef = playerController as PlayerTouchController;
|
|
|
|
// 3. Virtual hook: Setup
|
|
OnInteractionStarted();
|
|
|
|
// 4. Fire events
|
|
interactionStarted?.Invoke(playerRef, FollowerController);
|
|
await DispatchEventAsync(InteractionEventType.InteractionStarted, playerRef);
|
|
|
|
// 5. Orchestrate character movement
|
|
bool movementSucceeded = await MoveCharactersAsync(playerRef);
|
|
|
|
// If movement was cancelled, stop the interaction flow
|
|
if (!movementSucceeded)
|
|
{
|
|
Logging.Debug($"[Interactable] Interaction cancelled due to movement failure on {gameObject.name}");
|
|
return;
|
|
}
|
|
|
|
// 6. Virtual hook: Arrival reaction
|
|
OnInteractingCharacterArrived();
|
|
|
|
// 7. Fire arrival events
|
|
characterArrived?.Invoke();
|
|
await DispatchEventAsync(InteractionEventType.InteractingCharacterArrived, playerRef);
|
|
|
|
// 8. Validation (base + child)
|
|
var (canProceed, errorMessage) = ValidateInteraction();
|
|
if (!canProceed)
|
|
{
|
|
if (!string.IsNullOrEmpty(errorMessage))
|
|
{
|
|
DebugUIMessage.Show(errorMessage, Color.yellow);
|
|
}
|
|
FinishInteraction(false, playerRef);
|
|
return;
|
|
}
|
|
|
|
// 9. Virtual main logic: Do the thing!
|
|
bool success = DoInteraction();
|
|
|
|
// 10. Finish up
|
|
FinishInteraction(success, playerRef);
|
|
}
|
|
|
|
#region Virtual Lifecycle Methods
|
|
|
|
/// <summary>
|
|
/// High-level clickability check. Called BEFORE interaction starts.
|
|
/// Override to add custom high-level validation (is active, on cooldown, etc.)
|
|
/// </summary>
|
|
/// <returns>True if interaction can start, false for silent rejection</returns>
|
|
protected virtual bool CanBeClicked()
|
|
{
|
|
if (!isActive) return false;
|
|
// Note: isOneTime and cooldown handled in FinishInteraction
|
|
return true;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Called after characters are found but before movement starts.
|
|
/// Override to perform setup logic.
|
|
/// </summary>
|
|
protected virtual void OnInteractionStarted()
|
|
{
|
|
// Default: do nothing
|
|
}
|
|
|
|
/// <summary>
|
|
/// Called when the interacting character reaches destination.
|
|
/// Override to trigger animations or other arrival reactions.
|
|
/// </summary>
|
|
protected virtual void OnInteractingCharacterArrived()
|
|
{
|
|
// Default: do nothing
|
|
}
|
|
|
|
/// <summary>
|
|
/// Main interaction logic. OVERRIDE THIS in child classes.
|
|
/// </summary>
|
|
/// <returns>True if interaction succeeded, false otherwise</returns>
|
|
protected virtual bool DoInteraction()
|
|
{
|
|
Logging.Warning($"[Interactable] DoInteraction not implemented for {GetType().Name}");
|
|
return false;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Called after interaction completes. Override to perform cleanup logic.
|
|
/// </summary>
|
|
/// <param name="success">Whether the interaction succeeded</param>
|
|
protected virtual void OnInteractionFinished(bool success)
|
|
{
|
|
// Default: do nothing
|
|
}
|
|
|
|
/// <summary>
|
|
/// Child-specific validation. Override to add interaction-specific validation.
|
|
/// </summary>
|
|
/// <returns>Tuple of (canProceed, errorMessage)</returns>
|
|
protected virtual (bool canProceed, string errorMessage) CanProceedWithInteraction()
|
|
{
|
|
return (true, null); // Default: always allow
|
|
}
|
|
|
|
#endregion
|
|
|
|
#region Validation
|
|
|
|
/// <summary>
|
|
/// Combines base and child validation.
|
|
/// </summary>
|
|
private (bool, string) ValidateInteraction()
|
|
{
|
|
// Base validation (always runs)
|
|
var (baseValid, baseError) = ValidateInteractionBase();
|
|
if (!baseValid)
|
|
return (false, baseError);
|
|
|
|
// Child validation (optional override)
|
|
var (childValid, childError) = CanProceedWithInteraction();
|
|
if (!childValid)
|
|
return (false, childError);
|
|
|
|
return (true, null);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Base validation that always runs. Checks puzzle step locks and common prerequisites.
|
|
/// </summary>
|
|
private (bool canProceed, string errorMessage) ValidateInteractionBase()
|
|
{
|
|
// Check if there's an ObjectiveStepBehaviour attached
|
|
var step = GetComponent<PuzzleS.ObjectiveStepBehaviour>();
|
|
if (step != null && !step.IsStepUnlocked())
|
|
{
|
|
// Special case: ItemSlots can still be interacted with when locked (to swap items)
|
|
if (!(this is ItemSlot))
|
|
{
|
|
return (false, "This step is locked!");
|
|
}
|
|
}
|
|
|
|
return (true, null);
|
|
}
|
|
|
|
#endregion
|
|
|
|
#region Character Movement Orchestration
|
|
|
|
/// <summary>
|
|
/// Delegates movement to the interacting character's controller.
|
|
/// Each controller implements its own movement behavior based on this interactable's settings.
|
|
/// </summary>
|
|
/// <returns>True if movement succeeded, false if cancelled or failed</returns>
|
|
private async Task<bool> MoveCharactersAsync(PlayerTouchController playerRef = null)
|
|
{
|
|
if (_interactingCharacter == null)
|
|
{
|
|
Logging.Debug($"[Interactable] No interacting character found. Aborting interaction.");
|
|
interactionInterrupted.Invoke();
|
|
await DispatchEventAsync(InteractionEventType.InteractionInterrupted, playerRef);
|
|
return false;
|
|
}
|
|
|
|
// If characterToInteract is None, skip movement
|
|
if (characterToInteract == CharacterToInteract.None)
|
|
{
|
|
return true; // Continue to arrival
|
|
}
|
|
|
|
// Delegate to controller - let it decide how to handle the interaction
|
|
bool arrived = await _interactingCharacter.MoveToInteractableAsync(this);
|
|
|
|
if (!arrived)
|
|
{
|
|
Logging.Debug($"[Interactable] Movement cancelled for {gameObject.name}");
|
|
await HandleInteractionCancelledAsync(playerRef);
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Handles interaction being cancelled (player stopped moving).
|
|
/// </summary>
|
|
private async Task HandleInteractionCancelledAsync(PlayerTouchController playerRef = null)
|
|
{
|
|
interactionInterrupted?.Invoke();
|
|
await DispatchEventAsync(InteractionEventType.InteractionInterrupted, playerRef);
|
|
}
|
|
|
|
#endregion
|
|
|
|
#region Finalization
|
|
|
|
/// <summary>
|
|
/// Finalizes the interaction after DoInteraction completes.
|
|
/// </summary>
|
|
private async void FinishInteraction(bool success, PlayerTouchController playerRef = null)
|
|
{
|
|
// Virtual hook: Cleanup
|
|
OnInteractionFinished(success);
|
|
|
|
// Fire completion events
|
|
interactionComplete?.Invoke(success);
|
|
await DispatchEventAsync(InteractionEventType.InteractionComplete, playerRef);
|
|
|
|
// Handle one-time / cooldown
|
|
if (success)
|
|
{
|
|
if (isOneTime)
|
|
{
|
|
isActive = false;
|
|
}
|
|
else if (cooldown >= 0f)
|
|
{
|
|
StartCoroutine(HandleCooldown());
|
|
}
|
|
}
|
|
|
|
// Reset state
|
|
_interactingCharacter = null;
|
|
FollowerController = null;
|
|
}
|
|
|
|
private System.Collections.IEnumerator HandleCooldown()
|
|
{
|
|
isActive = false;
|
|
yield return new WaitForSeconds(cooldown);
|
|
isActive = true;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Enable or disable this interactable
|
|
/// </summary>
|
|
public void SetActive(bool active)
|
|
{
|
|
isActive = active;
|
|
}
|
|
|
|
#endregion
|
|
|
|
#region Legacy Methods & Compatibility
|
|
|
|
/// <summary>
|
|
/// DEPRECATED: Override DoInteraction() instead.
|
|
/// This method is kept temporarily for backward compatibility during migration.
|
|
/// </summary>
|
|
[Obsolete("Override DoInteraction() instead")]
|
|
protected virtual void OnCharacterArrived()
|
|
{
|
|
// Default implementation does nothing
|
|
// Children should override DoInteraction() in the new pattern
|
|
}
|
|
|
|
/// <summary>
|
|
/// Call this from subclasses to mark the interaction as complete.
|
|
/// NOTE: In the new pattern, just return true/false from DoInteraction().
|
|
/// This is kept for backward compatibility during migration.
|
|
/// </summary>
|
|
protected void CompleteInteraction(bool success)
|
|
{
|
|
// For now, this manually triggers completion
|
|
// After migration, DoInteraction() return value will replace this
|
|
interactionComplete?.Invoke(success);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Legacy method for backward compatibility.
|
|
/// </summary>
|
|
[Obsolete("Use CompleteInteraction instead")]
|
|
public void BroadcastInteractionComplete(bool success)
|
|
{
|
|
CompleteInteraction(success);
|
|
}
|
|
|
|
#endregion
|
|
|
|
#region ITouchInputConsumer Implementation
|
|
|
|
public void OnHoldStart(Vector2 position)
|
|
{
|
|
throw new NotImplementedException();
|
|
}
|
|
|
|
public void OnHoldMove(Vector2 position)
|
|
{
|
|
throw new NotImplementedException();
|
|
}
|
|
|
|
public void OnHoldEnd(Vector2 position)
|
|
{
|
|
throw new NotImplementedException();
|
|
}
|
|
|
|
#endregion
|
|
|
|
#if UNITY_EDITOR
|
|
/// <summary>
|
|
/// Draws gizmos for pickup interaction range in the editor.
|
|
/// </summary>
|
|
void OnDrawGizmos()
|
|
{
|
|
float playerStopDistance = characterToInteract == CharacterToInteract.Trafalgar
|
|
? AppleHills.SettingsAccess.GetPlayerStopDistanceDirectInteraction()
|
|
: AppleHills.SettingsAccess.GetPlayerStopDistance();
|
|
|
|
Gizmos.color = Color.yellow;
|
|
Gizmos.DrawWireSphere(transform.position, playerStopDistance);
|
|
GameObject playerObj = GameObject.FindGameObjectWithTag("Player");
|
|
if (playerObj != null)
|
|
{
|
|
Vector3 stopPoint = transform.position +
|
|
(playerObj.transform.position - transform.position).normalized * playerStopDistance;
|
|
Gizmos.color = Color.cyan;
|
|
Gizmos.DrawSphere(stopPoint, 0.15f);
|
|
}
|
|
}
|
|
#endif
|
|
}
|
|
}
|