562 lines
19 KiB
C#
562 lines
19 KiB
C#
using Interactions;
|
|
using UnityEngine;
|
|
using Pathfinding;
|
|
using UnityEngine.SceneManagement;
|
|
using Utils;
|
|
using AppleHills.Core.Settings;
|
|
|
|
/// <summary>
|
|
/// Controls the follower character, including following the player, handling pickups, and managing held items.
|
|
/// </summary>
|
|
public class FollowerController: MonoBehaviour
|
|
{
|
|
[Header("Follower Settings")]
|
|
public bool debugDrawTarget = true;
|
|
/// <summary>
|
|
/// How often to update follow logic.
|
|
/// </summary>
|
|
public float followUpdateInterval = 0.1f;
|
|
/// <summary>
|
|
/// Smoothing factor for manual movement.
|
|
/// </summary>
|
|
public float manualMoveSmooth = 8f;
|
|
|
|
// Settings reference
|
|
private IPlayerFollowerSettings _settings;
|
|
private IInteractionSettings _interactionSettings;
|
|
|
|
private GameObject _playerRef;
|
|
private Transform _playerTransform;
|
|
private AIPath _playerAIPath;
|
|
private AIPath _aiPath;
|
|
private Vector3 _targetPoint;
|
|
private float _timer;
|
|
private bool _isManualFollowing = true;
|
|
private Vector3 _lastMoveDir = Vector3.right;
|
|
// Direction variables for 2D blend tree animation
|
|
private float _lastDirX = 0f; // -1 (left) to 1 (right)
|
|
private float _lastDirY = -1f; // -1 (down) to 1 (up)
|
|
private float _currentSpeed = 0f;
|
|
private Animator _animator;
|
|
private Transform _artTransform;
|
|
private SpriteRenderer _spriteRenderer;
|
|
|
|
private PickupItemData _currentlyHeldItemData;
|
|
public PickupItemData CurrentlyHeldItemData => _currentlyHeldItemData;
|
|
private GameObject _cachedPickupObject = null;
|
|
public bool justCombined = false;
|
|
|
|
/// <summary>
|
|
/// Renderer for the held item icon.
|
|
/// </summary>
|
|
public SpriteRenderer heldObjectRenderer;
|
|
|
|
private bool _isReturningToPlayer = false;
|
|
private float _playerMaxSpeed = 5f;
|
|
private float _followerMaxSpeed = 6f;
|
|
private float _defaultFollowerMaxSpeed = 6f;
|
|
|
|
// Pickup events
|
|
public delegate void FollowerPickupHandler();
|
|
/// <summary>
|
|
/// Event fired when the follower arrives at a pickup.
|
|
/// </summary>
|
|
public event FollowerPickupHandler OnPickupArrived;
|
|
/// <summary>
|
|
/// Event fired when the follower returns to the player after a pickup.
|
|
/// </summary>
|
|
public event FollowerPickupHandler OnPickupReturned;
|
|
private Coroutine _pickupCoroutine;
|
|
|
|
private Input.PlayerTouchController _playerTouchController;
|
|
|
|
void Awake()
|
|
{
|
|
_aiPath = GetComponent<AIPath>();
|
|
// Find art prefab and animator
|
|
_artTransform = transform.Find("CharacterArt");
|
|
if (_artTransform != null)
|
|
{
|
|
_animator = _artTransform.GetComponent<Animator>();
|
|
_spriteRenderer = _artTransform.GetComponent<SpriteRenderer>();
|
|
}
|
|
else
|
|
{
|
|
_animator = GetComponentInChildren<Animator>(); // fallback
|
|
_spriteRenderer = GetComponentInChildren<SpriteRenderer>();
|
|
}
|
|
|
|
// Initialize settings references
|
|
_settings = GameManager.GetSettingsObject<IPlayerFollowerSettings>();
|
|
_interactionSettings = GameManager.GetSettingsObject<IInteractionSettings>();
|
|
}
|
|
|
|
void OnEnable()
|
|
{
|
|
SceneManager.sceneLoaded += OnSceneLoaded;
|
|
FindPlayerReference();
|
|
}
|
|
|
|
void OnDisable()
|
|
{
|
|
SceneManager.sceneLoaded -= OnSceneLoaded;
|
|
}
|
|
|
|
void OnSceneLoaded(Scene scene, LoadSceneMode mode)
|
|
{
|
|
FindPlayerReference();
|
|
}
|
|
|
|
void Update()
|
|
{
|
|
if (_playerTransform == null)
|
|
{
|
|
FindPlayerReference();
|
|
if (_playerTransform == null)
|
|
return;
|
|
}
|
|
|
|
_timer += Time.deltaTime;
|
|
if (_timer >= _settings.FollowUpdateInterval)
|
|
{
|
|
_timer = 0f;
|
|
UpdateFollowTarget();
|
|
}
|
|
|
|
if (_isManualFollowing)
|
|
{
|
|
Vector2 current2D = new Vector2(transform.position.x, transform.position.y);
|
|
Vector2 target2D = new Vector2(_targetPoint.x, _targetPoint.y);
|
|
float dist = Vector2.Distance(current2D, target2D);
|
|
float minSpeed = _followerMaxSpeed * 0.3f;
|
|
float lerpFactor = _settings.ManualMoveSmooth * Time.deltaTime;
|
|
float targetSpeed = 0f;
|
|
if (dist > _settings.StopThreshold)
|
|
{
|
|
if (dist > _settings.ThresholdFar)
|
|
{
|
|
targetSpeed = _followerMaxSpeed;
|
|
}
|
|
else if (dist > _settings.ThresholdNear && dist <= _settings.ThresholdFar)
|
|
{
|
|
targetSpeed = _followerMaxSpeed;
|
|
}
|
|
else if (dist > _settings.StopThreshold && dist <= _settings.ThresholdNear)
|
|
{
|
|
targetSpeed = minSpeed;
|
|
}
|
|
_currentSpeed = Mathf.Lerp(_currentSpeed, targetSpeed, lerpFactor);
|
|
if (dist > _settings.StopThreshold && dist <= _settings.ThresholdNear)
|
|
{
|
|
_currentSpeed = Mathf.Max(_currentSpeed, minSpeed);
|
|
}
|
|
Vector3 dir = (_targetPoint - transform.position).normalized;
|
|
transform.position += dir * _currentSpeed * Time.deltaTime;
|
|
}
|
|
else
|
|
{
|
|
_currentSpeed = 0f;
|
|
}
|
|
}
|
|
|
|
if (_isReturningToPlayer && _aiPath != null && _aiPath.enabled && _playerTransform != null)
|
|
{
|
|
_aiPath.destination = _playerTransform.position;
|
|
}
|
|
|
|
if (_animator != null)
|
|
{
|
|
float normalizedSpeed = 0f;
|
|
Vector3 velocity = Vector3.zero;
|
|
|
|
if (_isManualFollowing)
|
|
{
|
|
normalizedSpeed = _currentSpeed / _followerMaxSpeed;
|
|
|
|
// Calculate direction vector for manual movement
|
|
if (_currentSpeed > 0.01f)
|
|
{
|
|
velocity = (_targetPoint - transform.position).normalized * _currentSpeed;
|
|
}
|
|
}
|
|
else if (_aiPath != null)
|
|
{
|
|
normalizedSpeed = _aiPath.velocity.magnitude / _followerMaxSpeed;
|
|
velocity = _aiPath.velocity;
|
|
}
|
|
|
|
// Set speed parameter for idle/walk transitions
|
|
_animator.SetFloat("Speed", Mathf.Clamp01(normalizedSpeed));
|
|
|
|
// Calculate and set X and Y directions for 2D blend tree
|
|
if (velocity.sqrMagnitude > 0.01f)
|
|
{
|
|
// Normalize the velocity vector to get direction
|
|
Vector3 normalizedVelocity = velocity.normalized;
|
|
|
|
// Update the stored directions when actively moving
|
|
_lastDirX = normalizedVelocity.x;
|
|
_lastDirY = normalizedVelocity.y;
|
|
|
|
// Set the animator parameters
|
|
_animator.SetFloat("DirX", _lastDirX);
|
|
_animator.SetFloat("DirY", _lastDirY);
|
|
}
|
|
else
|
|
{
|
|
// When not moving, keep using the last direction
|
|
_animator.SetFloat("DirX", _lastDirX);
|
|
_animator.SetFloat("DirY", _lastDirY);
|
|
}
|
|
}
|
|
}
|
|
|
|
void FindPlayerReference()
|
|
{
|
|
GameObject playerObj = GameObject.FindGameObjectWithTag("Player");
|
|
if (playerObj != null)
|
|
{
|
|
_playerRef = playerObj;
|
|
_playerTransform = playerObj.transform;
|
|
_playerAIPath = playerObj.GetComponent<AIPath>();
|
|
_playerTouchController = playerObj.GetComponent<Input.PlayerTouchController>();
|
|
if (_playerAIPath != null)
|
|
{
|
|
_playerMaxSpeed = _playerAIPath.maxSpeed;
|
|
_defaultFollowerMaxSpeed = _playerMaxSpeed;
|
|
_followerMaxSpeed = _playerMaxSpeed * _settings.FollowerSpeedMultiplier;
|
|
}
|
|
}
|
|
else
|
|
{
|
|
_playerTransform = null;
|
|
_playerAIPath = null;
|
|
_playerTouchController = null;
|
|
}
|
|
}
|
|
|
|
#region Movement
|
|
/// <summary>
|
|
/// Updates the follower's target point to follow the player at a specified distance,
|
|
/// using the player's current movement direction if available. Disables pathfinding
|
|
/// when in manual following mode.
|
|
/// </summary>
|
|
void UpdateFollowTarget()
|
|
{
|
|
if (_playerTransform == null)
|
|
{
|
|
FindPlayerReference();
|
|
if (_playerTransform == null)
|
|
return;
|
|
}
|
|
if (_isManualFollowing)
|
|
{
|
|
Vector3 playerPos = _playerTransform.position;
|
|
Vector3 moveDir = Vector3.zero;
|
|
if (_playerAIPath != null && _playerAIPath.velocity.magnitude > 0.01f)
|
|
{
|
|
moveDir = _playerAIPath.velocity.normalized;
|
|
_lastMoveDir = moveDir;
|
|
}
|
|
else if (_playerTouchController != null && _playerTouchController.isHolding && _playerTouchController.LastDirectMoveDir.sqrMagnitude > 0.01f)
|
|
{
|
|
moveDir = _playerTouchController.LastDirectMoveDir;
|
|
_lastMoveDir = moveDir;
|
|
}
|
|
else
|
|
{
|
|
moveDir = _lastMoveDir;
|
|
}
|
|
// Use settings for followDistance
|
|
_targetPoint = playerPos - moveDir * _settings.FollowDistance;
|
|
_targetPoint.z = 0;
|
|
if (_aiPath != null)
|
|
{
|
|
_aiPath.enabled = false;
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Make the follower move to a specific point only. Will not automatically return.
|
|
/// </summary>
|
|
/// <param name="targetPosition">The position to move to.</param>
|
|
public void GoToPoint(Vector2 targetPosition)
|
|
{
|
|
if (_pickupCoroutine != null)
|
|
StopCoroutine(_pickupCoroutine);
|
|
if (_aiPath != null)
|
|
_aiPath.maxSpeed = _followerMaxSpeed;
|
|
_pickupCoroutine = StartCoroutine(GoToPointSequence(targetPosition));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Command follower to go to a specific point and return to player after a brief delay.
|
|
/// Legacy method that combines GoToPoint and ReturnToPlayer for backward compatibility.
|
|
/// </summary>
|
|
/// <param name="itemPosition">The position of the item to pick up.</param>
|
|
/// <param name="playerTransform">The transform of the player.</param>
|
|
public void GoToPointAndReturn(Vector2 itemPosition, Transform playerTransform)
|
|
{
|
|
if (_pickupCoroutine != null)
|
|
StopCoroutine(_pickupCoroutine);
|
|
if (_aiPath != null)
|
|
_aiPath.maxSpeed = _followerMaxSpeed;
|
|
_pickupCoroutine = StartCoroutine(PickupSequence(itemPosition, playerTransform));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Make the follower return to the player after it has reached a point.
|
|
/// </summary>
|
|
/// <param name="playerTransform">The transform of the player to return to.</param>
|
|
public void ReturnToPlayer(Transform playerTransform)
|
|
{
|
|
if (_pickupCoroutine != null)
|
|
StopCoroutine(_pickupCoroutine);
|
|
if (_aiPath != null)
|
|
_aiPath.maxSpeed = _followerMaxSpeed;
|
|
_pickupCoroutine = StartCoroutine(ReturnToPlayerSequence(playerTransform));
|
|
}
|
|
|
|
private System.Collections.IEnumerator PickupSequence(Vector2 itemPosition, Transform playerTransform)
|
|
{
|
|
_isManualFollowing = false;
|
|
_isReturningToPlayer = false;
|
|
if (_aiPath != null)
|
|
{
|
|
_aiPath.enabled = true;
|
|
_aiPath.maxSpeed = _followerMaxSpeed;
|
|
_aiPath.destination = new Vector3(itemPosition.x, itemPosition.y, 0);
|
|
}
|
|
// Wait until follower reaches item (2D distance)
|
|
while (Vector2.Distance(new Vector2(transform.position.x, transform.position.y), new Vector2(itemPosition.x, itemPosition.y)) > _settings.StopThreshold)
|
|
{
|
|
yield return null;
|
|
}
|
|
OnPickupArrived?.Invoke();
|
|
|
|
// Wait briefly, then return to player
|
|
yield return new WaitForSeconds(_interactionSettings.FollowerPickupDelay);
|
|
if (_aiPath != null && playerTransform != null)
|
|
{
|
|
_aiPath.maxSpeed = _followerMaxSpeed;
|
|
_aiPath.destination = playerTransform.position;
|
|
}
|
|
_isReturningToPlayer = true;
|
|
// Wait until follower returns to player (2D distance)
|
|
while (playerTransform != null && Vector2.Distance(new Vector2(transform.position.x, transform.position.y), new Vector2(playerTransform.position.x, playerTransform.position.y)) > _settings.StopThreshold)
|
|
{
|
|
yield return null;
|
|
}
|
|
_isReturningToPlayer = false;
|
|
OnPickupReturned?.Invoke();
|
|
// Reset follower speed to normal after pickup
|
|
_followerMaxSpeed = _defaultFollowerMaxSpeed;
|
|
if (_aiPath != null)
|
|
_aiPath.maxSpeed = _followerMaxSpeed;
|
|
_isManualFollowing = true;
|
|
if (_aiPath != null)
|
|
_aiPath.enabled = false;
|
|
_pickupCoroutine = null;
|
|
}
|
|
|
|
private System.Collections.IEnumerator GoToPointSequence(Vector2 targetPosition)
|
|
{
|
|
_isManualFollowing = false;
|
|
_isReturningToPlayer = false;
|
|
|
|
if (_aiPath != null)
|
|
{
|
|
_aiPath.enabled = true;
|
|
_aiPath.maxSpeed = _followerMaxSpeed;
|
|
_aiPath.destination = new Vector3(targetPosition.x, targetPosition.y, 0);
|
|
}
|
|
|
|
// Wait until follower reaches target
|
|
while (Vector2.Distance(new Vector2(transform.position.x, transform.position.y),
|
|
new Vector2(targetPosition.x, targetPosition.y)) > _settings.StopThreshold)
|
|
{
|
|
yield return null;
|
|
}
|
|
|
|
// Signal arrival
|
|
OnPickupArrived?.Invoke();
|
|
|
|
_pickupCoroutine = null;
|
|
}
|
|
|
|
private System.Collections.IEnumerator ReturnToPlayerSequence(Transform playerTransform)
|
|
{
|
|
if (_aiPath != null && playerTransform != null)
|
|
{
|
|
_aiPath.maxSpeed = _followerMaxSpeed;
|
|
_aiPath.destination = playerTransform.position;
|
|
}
|
|
|
|
_isReturningToPlayer = true;
|
|
|
|
// Wait until follower returns to player
|
|
while (playerTransform != null &&
|
|
Vector2.Distance(new Vector2(transform.position.x, transform.position.y),
|
|
new Vector2(playerTransform.position.x, playerTransform.position.y)) > _settings.StopThreshold)
|
|
{
|
|
yield return null;
|
|
}
|
|
|
|
_isReturningToPlayer = false;
|
|
OnPickupReturned?.Invoke();
|
|
|
|
// Reset follower speed to normal after pickup
|
|
_followerMaxSpeed = _defaultFollowerMaxSpeed;
|
|
if (_aiPath != null)
|
|
_aiPath.maxSpeed = _followerMaxSpeed;
|
|
_isManualFollowing = true;
|
|
if (_aiPath != null)
|
|
_aiPath.enabled = false;
|
|
|
|
_pickupCoroutine = null;
|
|
}
|
|
#endregion Movement
|
|
|
|
#region ItemInteractions
|
|
public void TryPickupItem(GameObject itemObject, PickupItemData itemData, bool dropItem = true)
|
|
{
|
|
if (_currentlyHeldItemData != null && _cachedPickupObject != null && dropItem)
|
|
{
|
|
// Drop the currently held item at the current position
|
|
DropHeldItemAt(transform.position);
|
|
}
|
|
// Pick up the new item
|
|
SetHeldItem(itemData, itemObject.GetComponent<SpriteRenderer>());
|
|
_cachedPickupObject = itemObject;
|
|
_cachedPickupObject.SetActive(false);
|
|
}
|
|
|
|
public enum CombinationResult
|
|
{
|
|
Successful,
|
|
Unsuccessful,
|
|
NotApplicable
|
|
}
|
|
|
|
public CombinationResult TryCombineItems(Pickup pickupA, out GameObject newItem)
|
|
{
|
|
newItem = null;
|
|
if (_cachedPickupObject == null)
|
|
{
|
|
return CombinationResult.NotApplicable;
|
|
}
|
|
Pickup pickupB = _cachedPickupObject.GetComponent<Pickup>();
|
|
if (pickupA == null || pickupB == null)
|
|
{
|
|
return CombinationResult.NotApplicable;
|
|
}
|
|
|
|
// Use the InteractionSettings directly instead of GameManager
|
|
CombinationRule matchingRule = _interactionSettings.GetCombinationRule(pickupA.itemData, pickupB.itemData);
|
|
|
|
Vector3 spawnPos = pickupA.gameObject.transform.position;
|
|
if (matchingRule != null && matchingRule.resultPrefab != null)
|
|
{
|
|
newItem = Instantiate(matchingRule.resultPrefab, spawnPos, Quaternion.identity);
|
|
PickupItemData itemData = newItem.GetComponent<Pickup>().itemData;
|
|
Destroy(pickupA.gameObject);
|
|
Destroy(pickupB.gameObject);
|
|
TryPickupItem(newItem, itemData);
|
|
return CombinationResult.Successful;
|
|
}
|
|
|
|
// If no combination found, return Unsuccessful
|
|
return CombinationResult.Unsuccessful;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Set the item held by the follower, copying all visual properties from the Pickup's SpriteRenderer.
|
|
/// </summary>
|
|
/// <param name="itemData">The item data to set.</param>
|
|
/// <param name="pickupRenderer">The SpriteRenderer from the Pickup to copy appearance from.</param>
|
|
public void SetHeldItem(PickupItemData itemData, SpriteRenderer pickupRenderer = null)
|
|
{
|
|
_currentlyHeldItemData = itemData;
|
|
if (heldObjectRenderer != null)
|
|
{
|
|
if (_currentlyHeldItemData != null && pickupRenderer != null)
|
|
{
|
|
AppleHillsUtils.CopySpriteRendererProperties(pickupRenderer, heldObjectRenderer);
|
|
}
|
|
else
|
|
{
|
|
heldObjectRenderer.sprite = null;
|
|
heldObjectRenderer.enabled = false;
|
|
}
|
|
}
|
|
}
|
|
|
|
public GameObject GetHeldPickupObject()
|
|
{
|
|
return _cachedPickupObject;
|
|
}
|
|
|
|
public void SetHeldItemFromObject(GameObject obj)
|
|
{
|
|
if (obj == null)
|
|
{
|
|
ClearHeldItem();
|
|
return;
|
|
}
|
|
var pickup = obj.GetComponent<Pickup>();
|
|
if (pickup != null)
|
|
{
|
|
SetHeldItem(pickup.itemData, pickup.iconRenderer);
|
|
_cachedPickupObject = obj;
|
|
}
|
|
else
|
|
{
|
|
ClearHeldItem();
|
|
}
|
|
}
|
|
|
|
public void ClearHeldItem()
|
|
{
|
|
_cachedPickupObject = null;
|
|
_currentlyHeldItemData = null;
|
|
if (heldObjectRenderer != null)
|
|
{
|
|
heldObjectRenderer.sprite = null;
|
|
heldObjectRenderer.enabled = false;
|
|
}
|
|
}
|
|
|
|
public void DropItem(FollowerController follower, Vector3 position)
|
|
{
|
|
var item = follower.GetHeldPickupObject();
|
|
if (item == null) return;
|
|
item.transform.position = position;
|
|
item.transform.SetParent(null);
|
|
item.SetActive(true);
|
|
follower.ClearHeldItem();
|
|
// Optionally: fire event, update UI, etc.
|
|
}
|
|
|
|
public void DropHeldItemAt(Vector3 position)
|
|
{
|
|
DropItem(this, position);
|
|
}
|
|
|
|
|
|
#endregion ItemInteractions
|
|
|
|
#if UNITY_EDITOR
|
|
void OnDrawGizmos()
|
|
{
|
|
if (debugDrawTarget && Application.isPlaying)
|
|
{
|
|
Gizmos.color = Color.cyan;
|
|
Gizmos.DrawSphere(_targetPoint, 0.2f);
|
|
Gizmos.color = Color.yellow;
|
|
Gizmos.DrawLine(transform.position, _targetPoint);
|
|
}
|
|
}
|
|
#endif
|
|
}
|