314 lines
10 KiB
C#
314 lines
10 KiB
C#
using UnityEngine;
|
|
using Pathfinding;
|
|
using UnityEngine.SceneManagement;
|
|
|
|
public class FollowerController : MonoBehaviour
|
|
{
|
|
[Header("Follower Settings")]
|
|
public float followDistance = 1.5f; // Desired distance behind player
|
|
public bool debugDrawTarget = true;
|
|
public float followUpdateInterval = 0.1f; // How often to update follow logic
|
|
public float manualMoveSmooth = 8f; // Smoothing factor for manual movement
|
|
|
|
private Transform playerTransform;
|
|
private AIPath playerAIPath;
|
|
private AIPath aiPath;
|
|
private Vector3 targetPoint;
|
|
private float timer;
|
|
private bool usePathfinding = false;
|
|
private bool isManualFollowing = true; // Default to manual following
|
|
private Vector3 lastMoveDir = Vector3.right; // Default direction
|
|
private float currentSpeed = 0f;
|
|
|
|
[Header("Speed Settings")]
|
|
public float acceleration = 10f;
|
|
public float deceleration = 12f;
|
|
public float thresholdFar = 2.5f;
|
|
public float thresholdNear = 0.5f;
|
|
public float stopThreshold = 0.1f; // Stop moving when within this distance
|
|
private float playerMaxSpeed = 5f;
|
|
private const float followerSpeedMultiplier = 1.2f;
|
|
private float followerMaxSpeed = 6f; // Default, will be set from player
|
|
private float defaultFollowerMaxSpeed = 6f; // Default fallback value
|
|
|
|
private Animator animator;
|
|
private Transform artTransform;
|
|
|
|
[Header("Held Item")]
|
|
public PickupItemData currentlyHeldItem;
|
|
public SpriteRenderer heldObjectRenderer;
|
|
|
|
void Awake()
|
|
{
|
|
aiPath = GetComponent<AIPath>();
|
|
// Find art prefab and animator
|
|
artTransform = transform.Find("CharacterArt");
|
|
if (artTransform != null)
|
|
{
|
|
animator = artTransform.GetComponent<Animator>();
|
|
}
|
|
else
|
|
{
|
|
animator = GetComponentInChildren<Animator>(); // fallback
|
|
}
|
|
}
|
|
|
|
void OnEnable()
|
|
{
|
|
SceneManager.sceneLoaded += OnSceneLoaded;
|
|
FindPlayerReference();
|
|
}
|
|
|
|
void OnDisable()
|
|
{
|
|
SceneManager.sceneLoaded -= OnSceneLoaded;
|
|
}
|
|
|
|
void OnSceneLoaded(Scene scene, LoadSceneMode mode)
|
|
{
|
|
FindPlayerReference();
|
|
}
|
|
|
|
void FindPlayerReference()
|
|
{
|
|
GameObject playerObj = GameObject.FindGameObjectWithTag("Player");
|
|
if (playerObj != null)
|
|
{
|
|
playerTransform = playerObj.transform;
|
|
playerAIPath = playerObj.GetComponent<AIPath>();
|
|
if (playerAIPath != null)
|
|
{
|
|
playerMaxSpeed = playerAIPath.maxSpeed;
|
|
defaultFollowerMaxSpeed = playerMaxSpeed;
|
|
followerMaxSpeed = playerMaxSpeed * followerSpeedMultiplier;
|
|
}
|
|
}
|
|
else
|
|
{
|
|
playerTransform = null;
|
|
playerAIPath = null;
|
|
}
|
|
}
|
|
|
|
void Start()
|
|
{
|
|
FindPlayerReference();
|
|
}
|
|
|
|
void UpdateFollowTarget()
|
|
{
|
|
if (playerTransform == null)
|
|
{
|
|
// Try to reacquire reference if lost
|
|
FindPlayerReference();
|
|
if (playerTransform == null)
|
|
return; // Still missing, skip update
|
|
}
|
|
if (isManualFollowing)
|
|
{
|
|
// Determine direction: use player's velocity if available, else lastMoveDir
|
|
Vector3 playerPos = playerTransform.position;
|
|
Vector3 moveDir = Vector3.zero;
|
|
if (playerAIPath != null && playerAIPath.velocity.magnitude > 0.01f)
|
|
{
|
|
moveDir = playerAIPath.velocity.normalized;
|
|
lastMoveDir = moveDir; // Update last valid direction
|
|
}
|
|
else
|
|
{
|
|
moveDir = lastMoveDir; // Use last direction if stationary
|
|
}
|
|
// Calculate target point behind player
|
|
targetPoint = playerPos - moveDir * followDistance;
|
|
targetPoint.z = 0; // For 2D
|
|
|
|
// Only disable aiPath if in manual mode
|
|
if (aiPath != null)
|
|
{
|
|
aiPath.enabled = false;
|
|
}
|
|
}
|
|
}
|
|
|
|
void Update()
|
|
{
|
|
if (playerTransform == null)
|
|
{
|
|
// Try to reacquire reference if lost
|
|
FindPlayerReference();
|
|
if (playerTransform == null)
|
|
return; // Still missing, skip update
|
|
}
|
|
|
|
timer += Time.deltaTime;
|
|
if (timer >= followUpdateInterval)
|
|
{
|
|
timer = 0f;
|
|
UpdateFollowTarget();
|
|
}
|
|
|
|
// Manual movement logic with acceleration/deceleration and stop threshold
|
|
if (isManualFollowing)
|
|
{
|
|
// 2D distance calculation (ignore z)
|
|
Vector2 current2D = new Vector2(transform.position.x, transform.position.y);
|
|
Vector2 target2D = new Vector2(targetPoint.x, targetPoint.y);
|
|
float dist = Vector2.Distance(current2D, target2D);
|
|
if (dist > stopThreshold)
|
|
{
|
|
float desiredSpeed = followerMaxSpeed;
|
|
if (dist > thresholdFar)
|
|
{
|
|
// Accelerate to follower's max speed
|
|
desiredSpeed = Mathf.Min(currentSpeed + acceleration * Time.deltaTime, followerMaxSpeed);
|
|
}
|
|
else if (dist <= thresholdNear && dist > stopThreshold)
|
|
{
|
|
// Decelerate as approaching target, but keep moving until stopThreshold
|
|
desiredSpeed = Mathf.Max(currentSpeed - deceleration * Time.deltaTime, 0.5f);
|
|
}
|
|
else
|
|
{
|
|
// Maintain follower's max speed
|
|
desiredSpeed = followerMaxSpeed;
|
|
}
|
|
currentSpeed = desiredSpeed;
|
|
Vector3 dir = (targetPoint - transform.position).normalized;
|
|
transform.position += dir * currentSpeed * Time.deltaTime;
|
|
}
|
|
else
|
|
{
|
|
// Stop moving when close enough
|
|
currentSpeed = 0f;
|
|
}
|
|
}
|
|
|
|
// Update animator speed parameter
|
|
if (animator != null)
|
|
{
|
|
float normalizedSpeed = 0f;
|
|
if (isManualFollowing)
|
|
{
|
|
// Use currentSpeed for manual following
|
|
normalizedSpeed = currentSpeed / followerMaxSpeed;
|
|
}
|
|
else if (aiPath != null)
|
|
{
|
|
// Use aiPath velocity for pathfinding mode
|
|
normalizedSpeed = aiPath.velocity.magnitude / followerMaxSpeed;
|
|
}
|
|
animator.SetFloat("Speed", Mathf.Clamp01(normalizedSpeed));
|
|
}
|
|
}
|
|
|
|
// Command follower to go to a specific point (pathfinding mode)
|
|
public void GoToPoint(Vector2 worldPosition)
|
|
{
|
|
isManualFollowing = false;
|
|
if (aiPath != null)
|
|
{
|
|
aiPath.enabled = true;
|
|
aiPath.maxSpeed = followerMaxSpeed;
|
|
aiPath.destination = new Vector3(worldPosition.x, worldPosition.y, 0);
|
|
}
|
|
}
|
|
|
|
public delegate void FollowerPickupHandler();
|
|
public event FollowerPickupHandler OnPickupArrived;
|
|
public event FollowerPickupHandler OnPickupReturned;
|
|
private Coroutine pickupCoroutine;
|
|
|
|
// Command follower to go to a specific point and return to player
|
|
public void GoToPointAndReturn(Vector2 itemPosition, Transform playerTransform)
|
|
{
|
|
if (pickupCoroutine != null)
|
|
StopCoroutine(pickupCoroutine);
|
|
if (aiPath != null)
|
|
aiPath.maxSpeed = followerMaxSpeed;
|
|
pickupCoroutine = StartCoroutine(PickupSequence(itemPosition, playerTransform));
|
|
}
|
|
|
|
public void SetHeldItem(PickupItemData itemData)
|
|
{
|
|
currentlyHeldItem = itemData;
|
|
if (heldObjectRenderer != null)
|
|
{
|
|
if (currentlyHeldItem != null && currentlyHeldItem.mapSprite != null)
|
|
{
|
|
heldObjectRenderer.sprite = currentlyHeldItem.mapSprite;
|
|
heldObjectRenderer.enabled = true;
|
|
}
|
|
else
|
|
{
|
|
heldObjectRenderer.sprite = null;
|
|
heldObjectRenderer.enabled = false;
|
|
}
|
|
}
|
|
}
|
|
|
|
private System.Collections.IEnumerator PickupSequence(Vector2 itemPosition, Transform playerTransform)
|
|
{
|
|
isManualFollowing = 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)) > stopThreshold)
|
|
{
|
|
yield return null;
|
|
}
|
|
OnPickupArrived?.Invoke();
|
|
// Set held item and destroy pickup
|
|
if (heldObjectRenderer != null)
|
|
{
|
|
// Find Pickup object at itemPosition
|
|
Collider2D[] hits = Physics2D.OverlapCircleAll(itemPosition, 0.2f);
|
|
foreach (var hit in hits)
|
|
{
|
|
var pickup = hit.GetComponent<Pickup>();
|
|
if (pickup != null)
|
|
{
|
|
SetHeldItem(pickup.itemData);
|
|
GameObject.Destroy(pickup.gameObject);
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
// Wait briefly, then return to player
|
|
yield return new WaitForSeconds(0.2f);
|
|
if (aiPath != null && playerTransform != null)
|
|
{
|
|
aiPath.maxSpeed = followerMaxSpeed;
|
|
aiPath.destination = playerTransform.position;
|
|
}
|
|
// 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)) > stopThreshold)
|
|
{
|
|
yield return null;
|
|
}
|
|
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;
|
|
}
|
|
|
|
void OnDrawGizmos()
|
|
{
|
|
if (debugDrawTarget && Application.isPlaying)
|
|
{
|
|
Gizmos.color = Color.cyan;
|
|
Gizmos.DrawSphere(targetPoint, 0.2f);
|
|
Gizmos.color = Color.yellow;
|
|
Gizmos.DrawLine(transform.position, targetPoint);
|
|
}
|
|
}
|
|
}
|