2026-05-21 보스 특수스킬1

This commit is contained in:
2026-05-21 15:22:07 +09:00
parent 0f35455ad7
commit a4a9316e9c
23 changed files with 533 additions and 39 deletions

View File

@@ -1,11 +1,7 @@
using System;
using UnityEngine;
// ============================================================================
// BossAttack
// ----------------------------------------------------------------------------
// 보스 공격 하나의 설정. 별도 .asset 없이 BossAI 인스펙터에서 배열로 편집.
// ============================================================================
[Serializable]
public class BossAttack
{
@@ -14,7 +10,7 @@ public class BossAttack
public float Range = 1.5f; // 타겟이 이 X거리 안일 때만 사용
public float Windup = 0.4f; // 공격 시작 ~ 데미지 발생 (선딜)
public float Duration = 0.9f; // 공격 동작 전체 길이 (이 동안 이동 정지)
public float Cooldown = 2f; // 이 공격 자체의 재사용 대기
public float Cooldown = 10f; // 이 공격 자체의 재사용 대기
public int Damage = 15;
public Vector2 HitVelocity = new Vector2(5f, 2f); // 피격자 넉백 (X는 보스 facing 방향으로 부호 적용)
public string AnimationState = "BossAttack";
@@ -23,10 +19,10 @@ public class BossAttack
// ============================================================================
// BossAI
// ----------------------------------------------------------------------------
// 보스의 두뇌. EnemyAI와 골격(감지→추격→공격)은 같지만:
// - 여러 공격(BossAttack 배열)을 보유하고, 사거리·쿨다운·페이즈 조건
// 만족하는 것 중 무작위로 골라 사용
// - 각 공격의 MinPhase로 페이즈 잠금 → Boss.CurrentPhase가 오르면 신규 공격 해금
// 보스의 두뇌. 감지 → 추격 → 공격 상태머신.
// - 단순 공격: BossAttack 데이터 배열 (사거리·쿨다운·페이즈 조건)
// - 특별 스킬: BossSkill 프리팹 배열. 시전 시 Instantiate → 끝나면 스스로 파괴
// - 행동 결정: 특별 스킬 → 단순 공격 → 추격 순으로 시도
// 같은 GameObject의 Enemy(몸)·Boss(페이즈)와 함께 동작.
// ============================================================================
[RequireComponent(typeof(Enemy))]
@@ -47,8 +43,9 @@ private enum AIState { Idle, Chase, Attack }
[Header("Attacks")]
[SerializeField] private BossAttack[] _attacks;
[SerializeField] private float _attackVerticalTolerance = 1.5f; // 공격 적중 인정 세로 오차
[SerializeField] private float _globalAttackCooldown = 0.6f; // 공격 종료 후 다음 공격까지 최소 간격
[SerializeField] private BossSkill[] _skillPrefabs; // 특별 스킬 프리팹 (시전 시 Instantiate)
[SerializeField] private float _attackVerticalTolerance = 1.5f; // 공격 적중 인정 세로 오차
[SerializeField] private float _globalAttackCooldown = 0.6f; // 공격/스킬 종료 후 다음 행동까지 최소 간격
[Header("Animation")]
[SerializeField] private string _idleAnimationState = "Idle";
@@ -65,13 +62,18 @@ private enum AIState { Idle, Chase, Attack }
private AIState _state = AIState.Idle;
private bool _hasAggro;
private float[] _attackCooldownTimers; // _attacks와 1:1 — 각 공격의 남은 쿨다운
private int[] _attackPickBuffer; // PickAttackIndex 후보 수집용 (GC 회피)
private float _globalCooldownTimer; // 공격 사이 전역 대기
private float[] _attackCooldownTimers; // _attacks와 1:1 — 각 공격의 남은 쿨다운
private int[] _attackPickBuffer; // PickAttackIndex 후보 수집용 (GC 회피)
private float[] _skillCooldownTimers; // _skillPrefabs와 1:1 — 보스별 스킬 쿨다운
private int[] _skillPickBuffer; // PickSkillIndex 후보 수집용 (GC 회피)
private float _globalCooldownTimer; // 공격/스킬 사이 전역 대기
private BossAttack _currentAttack; // 진행 중인 공격
private BossSkill _runningSkillInstance; // 진행 중인 스킬 인스턴스 (없거나 끝나면 null)
private bool _skillInProgress; // 스킬 시전 중 (인스턴스 생성 ~ 파괴)
private BossAttack _currentAttack; // 진행 중인 단순 공격
private bool _isAttacking;
private bool _attackDamageApplied; // 이번 공격에서 데미지를 이미 줬는지
private bool _attackDamageApplied; // 이번 공격에서 데미지를 이미 줬는지
private float _attackTimer;
private float _facingDirection = 1f;
@@ -86,9 +88,13 @@ private void Awake()
_anim = GetComponentInChildren<Animator>();
_spriteRenderer = GetComponentInChildren<SpriteRenderer>();
int count = _attacks != null ? _attacks.Length : 0;
_attackCooldownTimers = new float[count];
_attackPickBuffer = new int[count];
int attackCount = _attacks != null ? _attacks.Length : 0;
_attackCooldownTimers = new float[attackCount];
_attackPickBuffer = new int[attackCount];
int skillCount = _skillPrefabs != null ? _skillPrefabs.Length : 0;
_skillCooldownTimers = new float[skillCount];
_skillPickBuffer = new int[skillCount];
}
private void Update()
@@ -96,16 +102,29 @@ private void Update()
TickCooldowns();
ResolveTarget();
// 사망 / 행동 불가(피격 경직·잡힘) / 페이즈 전환 중 / 타겟 없음 → 정지.
// 사망 / 행동 불가(피격 경직·잡힘) / 페이즈 전환 중 / 타겟 없음 → 정지 + 진행 중 행동 취소.
if (_health.IsDead || !_enemy.CanUseAI
|| (_boss != null && _boss.IsTransitioning) || _target == null)
{
if (_isAttacking) CancelAttack();
CancelRunningSkill();
StopMoving();
SetState(AIState.Idle);
return;
}
// 특별 스킬 진행 중이면 스킬에 전부 맡기고 대기. 인스턴스가 사라지면(종료) 후딜 부여.
if (_skillInProgress)
{
if (_runningSkillInstance != null)
{
StopMoving();
return;
}
_skillInProgress = false;
_globalCooldownTimer = _globalAttackCooldown;
}
RefreshAggro();
// 공격 중이면 facing을 고정한 채 공격 진행만 처리.
@@ -124,12 +143,25 @@ private void Update()
return;
}
// 사용 가능한 공격이 있으면 공격 시작, 없으면 추격.
int attackIndex = _globalCooldownTimer <= 0f ? PickAttackIndex() : -1;
if (attackIndex >= 0)
BeginAttack(attackIndex);
else
SetState(AIState.Chase);
// 전역 쿨다운이 끝났으면 특별 스킬 → 단순 공격 순으로 시도. 둘 다 안 되면 추격.
if (_globalCooldownTimer <= 0f)
{
int skillIndex = PickSkillIndex();
if (skillIndex >= 0)
{
BeginSkill(skillIndex);
return;
}
int attackIndex = PickAttackIndex();
if (attackIndex >= 0)
{
BeginAttack(attackIndex);
return;
}
}
SetState(AIState.Chase);
}
private void FixedUpdate()
@@ -146,7 +178,7 @@ private void FixedUpdate()
_rb.linearVelocity = v;
}
// ─── 공격 ────────────────────────────────────────────────────────────
// ─── 단순 공격 ────────────────────────────────────────────────────────
// 현재 사용 가능한 공격 후보 중 무작위 1개의 인덱스 반환. 없으면 -1.
// 조건: 페이즈 해금 + 쿨다운 종료 + 사거리 안.
@@ -181,7 +213,7 @@ private void BeginAttack(int index)
_attackDamageApplied = false;
_attackTimer = 0f;
_attackCooldownTimers[index] = _currentAttack.Cooldown;
// 공격 동작 길이 + 후딜만큼 다음 공격을 막는다.
// 공격 동작 길이 + 후딜만큼 다음 행동을 막는다.
_globalCooldownTimer = _currentAttack.Duration + _globalAttackCooldown;
_state = AIState.Attack;
@@ -234,16 +266,80 @@ private void ApplyAttackDamage()
_targetDamageable.TakeDamage(_currentAttack.Damage, knockback);
}
// ─── 특별 스킬 ───────────────────────────────────────────────────────
// 사용 가능한 스킬 프리팹 후보 중 무작위 1개의 인덱스 반환. 없으면 -1.
// 조건은 프리팹에서 직접 읽는다 (MinPhase/Range). 쿨다운은 보스별 타이머로.
private int PickSkillIndex()
{
if (_skillPrefabs == null || _skillPrefabs.Length == 0 || _target == null) return -1;
float distanceX = Mathf.Abs(_target.position.x - transform.position.x);
int phase = _boss != null ? _boss.CurrentPhase : 0;
int candidateCount = 0;
for (int i = 0; i < _skillPrefabs.Length; i++)
{
BossSkill prefab = _skillPrefabs[i];
if (prefab == null) continue;
if (phase < prefab.MinPhase) continue; // 페이즈 미해금
if (_skillCooldownTimers[i] > 0f) continue; // 쿨다운 중
if (distanceX > prefab.Range) continue; // 사거리 밖
_skillPickBuffer[candidateCount++] = i;
}
if (candidateCount == 0) return -1;
return _skillPickBuffer[UnityEngine.Random.Range(0, candidateCount)];
}
private void BeginSkill(int index)
{
BossSkill prefab = _skillPrefabs[index];
_skillCooldownTimers[index] = prefab.Cooldown;
_state = AIState.Idle;
StopMoving();
UpdateFacing(); // _facingDirection을 타겟 방향으로 갱신
// 스킬 프리팹을 보스 위치에 생성하고 보스의 자식으로 둔다 (보스 파괴 시 함께 정리).
BossSkill instance = Instantiate(prefab, transform.position, Quaternion.identity, transform);
// 보스가 왼쪽을 보면 스킬도 X 반전 (콜라이더 패턴이 시전 방향을 따르게).
if (_facingDirection < 0f)
{
Vector3 scale = instance.transform.localScale;
scale.x = -Mathf.Abs(scale.x);
instance.transform.localScale = scale;
}
_runningSkillInstance = instance;
_skillInProgress = true;
PlayAnim(prefab.CasterAnimationState); // 보스는 시전 애니메이션 재생
instance.Begin();
}
// 진행 중인 스킬 인스턴스를 파괴해 즉시 중단 (콜라이더도 함께 사라짐).
private void CancelRunningSkill()
{
if (_runningSkillInstance != null)
Destroy(_runningSkillInstance.gameObject);
_runningSkillInstance = null;
_skillInProgress = false;
}
private void TickCooldowns()
{
if (_globalCooldownTimer > 0f)
_globalCooldownTimer -= Time.deltaTime;
for (int i = 0; i < _attackCooldownTimers.Length; i++)
{
if (_attackCooldownTimers[i] > 0f)
_attackCooldownTimers[i] -= Time.deltaTime;
}
for (int i = 0; i < _skillCooldownTimers.Length; i++)
if (_skillCooldownTimers[i] > 0f)
_skillCooldownTimers[i] -= Time.deltaTime;
}
// ─── 타겟 / 인지 / 방향 ──────────────────────────────────────────────
@@ -306,7 +402,7 @@ private void SetState(AIState state)
_state = state;
if (state == AIState.Idle) PlayAnim(_idleAnimationState);
else if (state == AIState.Chase) PlayAnim(_runAnimationState);
// Attack 상태 애니메이션은 BeginAttack에서 직접 재생.
// Attack 상태 애니메이션은 BeginAttack, 스킬 시전 애니메이션은 BeginSkill에서 재생.
}
// 같은 State 중복 재생 방지 (Play를 매 프레임 호출하면 애니가 처음으로 리셋됨).
@@ -324,10 +420,16 @@ private void OnDrawGizmosSelected()
Gizmos.color = Color.yellow;
Gizmos.DrawWireSphere(transform.position, _detectRange);
if (_attacks == null) return;
Gizmos.color = Color.red;
for (int i = 0; i < _attacks.Length; i++)
if (_attacks[i] != null)
Gizmos.DrawWireSphere(transform.position, _attacks[i].Range);
if (_attacks != null)
for (int i = 0; i < _attacks.Length; i++)
if (_attacks[i] != null)
Gizmos.DrawWireSphere(transform.position, _attacks[i].Range);
Gizmos.color = new Color(1f, 0.4f, 1f); // 스킬 사거리 = 보라색
if (_skillPrefabs != null)
for (int i = 0; i < _skillPrefabs.Length; i++)
if (_skillPrefabs[i] != null)
Gizmos.DrawWireSphere(transform.position, _skillPrefabs[i].Range);
}
}