ShantiManti/Assets/game/enemy/Bird/scripts/EnemyAI.cs
2024-12-07 18:41:57 +01:00

90 lines
2.2 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Pathfinding;
public class EnemyAI : MonoBehaviour
{
public Transform target;
public float speed = 200f;
public float nextWaypointDistance = 3f;
private Transform enemyGFX;
Path path;
int currentWaypoint = 0;
// ↓ uncomment every comment with reachedEndOfPath if you need it. In this case it isnt usefull
//bool reachedEndOfPath = false;
Seeker seeker;
Rigidbody2D rb;
void Start()
{
seeker = GetComponent<Seeker>();
rb = GetComponent<Rigidbody2D>();
enemyGFX = GetComponentInChildren<SpriteRenderer>().transform;
InvokeRepeating("UpdatePath", 0f, .5f);
}
void UpdatePath()
{
if (seeker.IsDone())
{
seeker.StartPath(rb.position, target.position, OnPathComplete);
}
}
void OnPathComplete (Path p)
{
if (!p.error)
{
path = p;
currentWaypoint = 0;
}
}
void FixedUpdate()
{
if (Pause.IsPause == false)
{
if (path == null)
{
return;
}
if (currentWaypoint >= path.vectorPath.Count)
{
//reachedEndOfPath = true;
return;
}
else
{
//reachedEndOfPath = false;
}
Vector2 direction = ((Vector2)path.vectorPath[currentWaypoint] -rb.position).normalized;
Vector2 force = direction * speed * Time.deltaTime;
rb.AddForce(force);
float distance = Vector2.Distance(rb.position, path.vectorPath[currentWaypoint]);
if (distance < nextWaypointDistance)
{
currentWaypoint++;
}
//You can make look it differently, if you delete 'rb.velocity' and add 'force' instead.
if (rb.linearVelocity.x >= 0.01f)
{
enemyGFX.transform.localScale = new Vector3(-1f, 1f, 1f);
}
else if (rb.linearVelocity.x <= -0.01f)
{
enemyGFX.transform.localScale = new Vector3(1f, 1f, 1f);
}
}
}
}