fgm24/Assets/Scripts/Enemy/EnemyPathFinding.cs

90 lines
2.4 KiB
C#
Raw Permalink Normal View History

2024-02-04 06:50:33 +01:00
using System;
2024-02-02 23:21:12 +01:00
using System.Collections;
using System.Collections.Generic;
using System.Linq;
2024-02-02 23:21:12 +01:00
using UnityEngine;
using UnityEngine.AI;
public class EnemyPathFinding : MonoBehaviour
{
2024-02-03 22:31:54 +01:00
[SerializeField] public Transform[] targets;
[SerializeField] private float ropeDistCheck = 1f;
2024-06-01 16:26:03 +02:00
//[SerializeField] private float stopBeforeTargetOffset = 1f; //Unused
[SerializeField] private LayerMask ropeCheckMask;
2024-03-01 21:56:46 +01:00
private bool isCollidingWithTarget;
2024-02-02 23:21:12 +01:00
2024-02-04 06:50:33 +01:00
private HealthComponent healthComponent;
2024-02-02 23:21:12 +01:00
NavMeshAgent agent;
private void Start()
{
agent = GetComponent<NavMeshAgent>();
agent.updateRotation = false;
agent.updateUpAxis = false;
2024-03-01 21:56:46 +01:00
agent.baseOffset = 0;
2024-02-04 06:50:33 +01:00
healthComponent = GetComponent<HealthComponent>();
healthComponent.OnHealthZero.AddListener(Rumble);
2024-03-01 21:56:46 +01:00
2024-02-04 06:50:33 +01:00
}
private void Rumble()
{
2024-02-04 10:24:38 +01:00
RumbleManager.StartRumble(-1, 0.5f, 0.5f, 0.25f);
2024-02-04 11:46:40 +01:00
CameraShaker.ShakecShake(0.1f, 0.25f);
2024-02-02 23:21:12 +01:00
}
2024-02-04 06:50:33 +01:00
2024-02-02 23:21:12 +01:00
private void Update()
{
2024-02-03 21:52:24 +01:00
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;
2024-02-03 21:52:24 +01:00
if (Physics2D.Raycast(transform.position, dir.normalized, ropeDistCheck, ropeCheckMask)) return;
2024-03-01 21:56:46 +01:00
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;
2024-02-02 23:21:12 +01:00
}
2024-03-01 21:56:46 +01:00
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;
}
}
2024-02-02 23:21:12 +01:00
}