90 lines
2.4 KiB
C#
90 lines
2.4 KiB
C#
using System;
|
|
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using UnityEngine;
|
|
using UnityEngine.AI;
|
|
|
|
public class EnemyPathFinding : MonoBehaviour
|
|
{
|
|
[SerializeField] public Transform[] targets;
|
|
|
|
[SerializeField] private float ropeDistCheck = 1f;
|
|
//[SerializeField] private float stopBeforeTargetOffset = 1f; //Unused
|
|
[SerializeField] private LayerMask ropeCheckMask;
|
|
private bool isCollidingWithTarget;
|
|
|
|
private HealthComponent healthComponent;
|
|
|
|
NavMeshAgent agent;
|
|
private void Start()
|
|
{
|
|
agent = GetComponent<NavMeshAgent>();
|
|
agent.updateRotation = false;
|
|
agent.updateUpAxis = false;
|
|
agent.baseOffset = 0;
|
|
|
|
healthComponent = GetComponent<HealthComponent>();
|
|
healthComponent.OnHealthZero.AddListener(Rumble);
|
|
|
|
}
|
|
|
|
private void Rumble()
|
|
{
|
|
RumbleManager.StartRumble(-1, 0.5f, 0.5f, 0.25f);
|
|
CameraShaker.ShakecShake(0.1f, 0.25f);
|
|
}
|
|
|
|
private void Update()
|
|
{
|
|
if (targets.Length == 0) return;
|
|
|
|
Transform closestTarget = GetClosestTarget();
|
|
if (closestTarget == null) return;
|
|
|
|
// Make sure no rope parts are in front
|
|
Vector2 dir = closestTarget.position - transform.position;
|
|
if (Physics2D.Raycast(transform.position, dir.normalized, ropeDistCheck, ropeCheckMask)) return;
|
|
|
|
try
|
|
{
|
|
if (!isCollidingWithTarget)
|
|
agent.SetDestination(closestTarget.position);
|
|
}
|
|
catch { }// Fuck this error.
|
|
}
|
|
|
|
private Transform GetClosestTarget()
|
|
{
|
|
float dist = Mathf.Infinity;
|
|
Transform shortest = targets[0];
|
|
foreach (var target in targets)
|
|
{
|
|
float targetDist = Vector2.Distance(target.position, transform.position);
|
|
if (targetDist < dist)
|
|
{
|
|
dist = targetDist;
|
|
shortest = target;
|
|
}
|
|
}
|
|
return shortest;
|
|
}
|
|
|
|
private void OnCollisionEnter2D(Collision2D collision)
|
|
{
|
|
if (collision.gameObject.CompareTag("Player"))
|
|
{
|
|
isCollidingWithTarget = true;
|
|
agent.stoppingDistance = 100;
|
|
}
|
|
}
|
|
private void OnCollisionExit2D(Collision2D collision)
|
|
{
|
|
if (collision.gameObject.CompareTag("Player"))
|
|
{
|
|
isCollidingWithTarget = false;
|
|
agent.stoppingDistance = 0;
|
|
}
|
|
}
|
|
}
|