Files
GoblinRaid/Assets/Scripts/Combat/Fighter.cs

86 lines
2.4 KiB
C#
Raw Normal View History

2025-10-27 17:05:16 +00:00
using UnityEngine;
using RPG.Movement;
2025-10-27 17:26:17 +00:00
using UnityEngine.Rendering;
2025-10-28 17:26:07 +00:00
using RPG.Core;
2025-10-27 17:05:16 +00:00
namespace RPG.Combat
2025-10-27 17:26:17 +00:00
{
2025-10-28 17:26:07 +00:00
public class Fighter : MonoBehaviour, IAction
2025-10-27 17:05:16 +00:00
{
2025-10-28 17:26:07 +00:00
[SerializeField] private float timeBetweenAttacks = 1f;
[SerializeField] private float weaponRange = 2f;
[SerializeField] private float weaponDamage = 5f;
Health target;
2025-10-30 16:50:35 +00:00
private float timeSinceLastAttack = Mathf.Infinity;
2025-10-28 17:26:07 +00:00
void Update()
2025-10-27 17:05:16 +00:00
{
2025-10-28 17:26:07 +00:00
timeSinceLastAttack += Time.deltaTime;
2025-10-27 17:26:17 +00:00
if (target == null) return;
2025-10-28 17:26:07 +00:00
if (target.IsDead()) return;
2025-10-27 17:26:17 +00:00
if (!GetIsInRange())
2025-10-27 17:05:16 +00:00
{
2025-10-28 17:26:07 +00:00
GetComponent<Mover>().MoveTo(target.transform.position);
2025-10-27 17:05:16 +00:00
}
2025-10-27 17:26:17 +00:00
else
{
2025-10-28 17:26:07 +00:00
GetComponent<Mover>().Cancel();
AttackBehaviour();
2025-10-27 17:26:17 +00:00
}
}
2025-10-28 17:26:07 +00:00
private void AttackBehaviour()
{
transform.LookAt(target.transform);
if (timeSinceLastAttack > timeBetweenAttacks)
{
//This will trigger the Hit() event.
TriggerAttack();
timeSinceLastAttack = 0;
}
else return;
}
private void TriggerAttack()
{
GetComponent<Animator>().ResetTrigger("stopAttack");
GetComponent<Animator>().SetTrigger("attack");
}
//Animation event
void Hit()
{
if (target == null) return;
target.TakeDamage(weaponDamage);
}
2025-10-27 17:26:17 +00:00
private bool GetIsInRange()
{
2025-10-28 17:26:07 +00:00
return Vector3.Distance(transform.position, target.transform.position) <= weaponRange;
2025-10-27 17:05:16 +00:00
}
2025-10-27 17:26:17 +00:00
2025-10-28 17:26:07 +00:00
public bool CanAttack(GameObject combatTarget)
2025-10-27 17:05:16 +00:00
{
2025-10-28 17:26:07 +00:00
if (combatTarget == null) return false;
Health targetToTest = combatTarget.GetComponent<Health>();
return targetToTest != null && !targetToTest.IsDead();
}
public void Attack(GameObject combatTarget)
{
GetComponent<ActionScheduler>().StartAction(this);
target = combatTarget.GetComponent<Health>();
2025-10-27 17:05:16 +00:00
}
2025-10-27 17:26:17 +00:00
public void Cancel()
{
2025-10-28 17:26:07 +00:00
StopAttack();
target = null;
}
private void StopAttack()
{
GetComponent<Animator>().ResetTrigger("attack");
GetComponent<Animator>().SetTrigger("stopAttack");
2025-10-27 17:26:17 +00:00
}
2025-10-27 17:05:16 +00:00
}
}