Quelques trucs pour structuer
This commit is contained in:
parent
af46b49095
commit
1165e50bb5
15 changed files with 245 additions and 2 deletions
62
Assets/Scripts/AttackHandler.cs
Normal file
62
Assets/Scripts/AttackHandler.cs
Normal file
|
@ -0,0 +1,62 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
public class AttackHandler : MonoBehaviour
|
||||
{
|
||||
[SerializeField] private float damage;
|
||||
[SerializeField] private float cooldown;
|
||||
[SerializeField] private Collider attackShape;
|
||||
|
||||
private float _timer;
|
||||
|
||||
void Start()
|
||||
{
|
||||
_timer = cooldown;
|
||||
}
|
||||
|
||||
void Update()
|
||||
{
|
||||
_timer = Mathf.Max(_timer - Time.deltaTime, 0f);
|
||||
}
|
||||
|
||||
public bool Attack()
|
||||
{
|
||||
if (_timer >= 0) return false;
|
||||
Collider[] targets = DetectTargets();
|
||||
foreach (Collider target in targets)
|
||||
{
|
||||
if (!target.CompareTag("Unit")) continue;
|
||||
// GetComponent is expensive in performance, optimize here if it's slow
|
||||
Unit unit = target.GetComponent<Unit>();
|
||||
unit.healthHandler.TakeDamage(damage);
|
||||
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private Collider[] DetectTargets()
|
||||
{
|
||||
// Make sure to manager layers for better performance
|
||||
|
||||
List<Unit> targets = new List<Unit>();
|
||||
Collider[] hitColliders;
|
||||
|
||||
switch (attackShape)
|
||||
{
|
||||
case SphereCollider sphere:
|
||||
hitColliders = Physics.OverlapSphere(sphere.transform.position, sphere.radius, sphere.includeLayers);
|
||||
break;
|
||||
case BoxCollider box:
|
||||
hitColliders = Physics.OverlapBox(box.bounds.center, box.bounds.extents, box.transform.rotation, box.includeLayers);
|
||||
break;
|
||||
default:
|
||||
throw new ArgumentException("Only sphere or box are supported");
|
||||
}
|
||||
|
||||
return hitColliders;
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue