본문 바로가기

TIL

[ 24.08.05 ] 내일배움캠프 TIL - 코루틴, 회전

[ ps ]

 

[ 백준 / C++ ] 7662 : 이중 우선순위 큐 (tistory.com)

 

[ Unity ]

 

Player 가 공격을 하면 ComboAttackState에 들어가고, 콤보에 맞는 행동을 진행하게 된다. (FSM)

 

이 과정에서 각 콤보에 맞는 WeaponHitBox ( 플레이어 무기 Collider ) 를 활성화하고 비활성화하는데,

Player 공격이 좀 더 스무스하게 보이기 위해 활성화 하기 직전에 대기 시간을 주고 싶었다.

 

이를 활용하기 위해 코루틴을 사용하였다.

public void WeaponHitBoxEnabled()
{
    coroutine = StartCoroutine(WeaponHitBoxFlash());
}

public void WeaponHitBoxDisabled()
{
    if (coroutine != null) StopCoroutine(coroutine);
    weaponHitBox.enabled = false;
}

IEnumerator WeaponHitBoxFlash()
{
    yield return new WaitForSeconds(effectStart);
    weaponHitBox.enabled = true;
}

 

구현 과정에서 공격을 짧은 시간에 여러번 하게 되면 WeaponHitBox 비활성화가 제대로 작동하지 않는 오류를 발견했다.

 

코루틴이 다 끝나기 전에 비활성화 메서드를 호출됨으로서 코드가 씹히는 현상으로 추정하였고,

위처럼 비활성화 과정에서 StopCoroutine 메서드를 활용하여 오류를 해결하였다.

 

두 번째로 Player 가 공격에 성공하였을 때 나오는 이펙트를 Enemy 위치에 대응하여 회전시키고 싶었다.

 

아래와 같이 충돌한 두 오브젝트( Player, Enemy )의 월드 좌표를 가져와서 방향벡터를 구하고,
이를 통해 회전해야 하는 각도를 계산하였다.

 

private void OnTriggerEnter2D(Collider2D collision)
{
    if (collision.CompareTag(targetTag))
    {
        if (collision.TryGetComponent<EnemyComponent>(out EnemyComponent enemy))
        {
            enemy.OnHit(damage);
        }

        startPosition = player.transform.position;
        endPosition = collision.transform.position;
        direction = (endPosition - startPosition).normalized;
        angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
        
        attackEffect.transform.rotation = Quaternion.Euler(0, 0, angle);

        StartCoroutine(AttackEffectFlash());
    }
}