104 lines
3.2 KiB
C#
104 lines
3.2 KiB
C#
using UnityEngine;
|
|
using System;
|
|
using Pathfinding;
|
|
|
|
public class AnneLiseBehaviour : MonoBehaviour
|
|
{
|
|
[SerializeField] public float moveSpeed;
|
|
private Animator animator;
|
|
private AIPath aiPath;
|
|
private bool hasArrived = false;
|
|
private GameObject currentLureSpot;
|
|
private SpriteRenderer spriteRenderer; // Cached reference
|
|
private bool allowFacingByVelocity = true; // New flag
|
|
|
|
private void Awake()
|
|
{
|
|
animator = GetComponentInChildren<Animator>();
|
|
aiPath = GetComponent<AIPath>();
|
|
spriteRenderer = GetComponentInChildren<SpriteRenderer>(); // Cache the reference
|
|
if (aiPath != null)
|
|
{
|
|
aiPath.maxSpeed = moveSpeed;
|
|
}
|
|
}
|
|
|
|
public void GotoSpot(GameObject lurespot)
|
|
{
|
|
if (aiPath == null) return;
|
|
|
|
aiPath.destination = lurespot.transform.position;
|
|
aiPath.canMove = true;
|
|
aiPath.SearchPath();
|
|
hasArrived = false;
|
|
allowFacingByVelocity = true; // Enable facing by velocity when moving
|
|
currentLureSpot = lurespot;
|
|
}
|
|
|
|
private void Update()
|
|
{
|
|
if (aiPath == null || animator == null) return;
|
|
|
|
float currentSpeed = aiPath.velocity.magnitude;
|
|
animator.SetFloat("speed", currentSpeed);
|
|
|
|
// Only allow facing by velocity if not arrived
|
|
if (allowFacingByVelocity && currentSpeed > 0.01f && spriteRenderer != null)
|
|
{
|
|
Vector3 velocity = aiPath.velocity;
|
|
if (velocity.x != 0)
|
|
{
|
|
Vector3 scale = spriteRenderer.transform.localScale;
|
|
scale.x = Mathf.Abs(scale.x) * (velocity.x > 0 ? 1 : -1);
|
|
spriteRenderer.transform.localScale = scale;
|
|
}
|
|
}
|
|
|
|
if (!hasArrived && aiPath.reachedDestination && currentSpeed < 0.01f)
|
|
{
|
|
hasArrived = true;
|
|
allowFacingByVelocity = false; // Disable facing by velocity after arrival
|
|
OnArriveAtSpot();
|
|
aiPath.canMove = false;
|
|
}
|
|
}
|
|
|
|
private void OnArriveAtSpot()
|
|
{
|
|
// Face the "BirdSpawned" child of the current lurespot, if available
|
|
if (currentLureSpot != null)
|
|
{
|
|
GameObject birdSpawned = null;
|
|
foreach (Transform child in currentLureSpot.GetComponentsInChildren<Transform>(true))
|
|
{
|
|
if (child.name == "BirdSpawned")
|
|
{
|
|
birdSpawned = child.gameObject;
|
|
break;
|
|
}
|
|
}
|
|
if (birdSpawned != null)
|
|
{
|
|
FaceTarget(birdSpawned);
|
|
}
|
|
}
|
|
|
|
if (animator != null)
|
|
animator.SetTrigger("TakePhoto");
|
|
}
|
|
|
|
public void FaceTarget(GameObject target)
|
|
{
|
|
if (target == null || spriteRenderer == null) return;
|
|
|
|
// Compare X positions to determine facing direction
|
|
float direction = target.transform.position.x - transform.position.x;
|
|
if (Mathf.Abs(direction) > 0.01f) // Avoid flipping if almost aligned
|
|
{
|
|
Vector3 scale = spriteRenderer.transform.localScale;
|
|
scale.x = Mathf.Abs(scale.x) * (direction > 0 ? 1 : -1);
|
|
spriteRenderer.transform.localScale = scale;
|
|
}
|
|
}
|
|
}
|