쾌락없는 책임 (공부)/Unity

유니티 - 보스몬스터 패턴 1 : 플레이어 감지 후 공격

허스크 2021. 1. 3. 15:57
반응형

움짤은 용량이 커서 화질이 구리다

<설정>

- 보스 몬스터의 하위 오브젝트로 빈 오브젝트가 있음

    - 이 빈 오브젝트에 공격 코드가 달려있으며 OnTriggerStay를 사용하기 위해 tirgger로 만듬

- 소환되는 경고창과 공격(사진에서 몬스터)에 Destroy하는 스크립트가 있음

    - 이건 프리팹으로 미리 만들어 둔 것

 

<소스코드>

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BossMonsterPattern : MonoBehaviour
{
    private bool isAttacking = false;
    Vector3 playerPos;
    Vector3 whereToAtk;
    public GameObject warning;
    public GameObject Atk1;
    private void OnTriggerStay2D(Collider2D other) {
        if(other.tag == "Player"){
            playerPos = other.transform.position;
            StartCoroutine("BeforeAttack");
        }
            
    }

    // OntriggerStay는 프레임 단위로 실행되기 때문에 코루틴을 이용
    // isAttacking 변수를 이용해 false일때만 공격을 하도록 설정
    IEnumerator BeforeAttack(){
        if(isAttacking == false) {
            whereToAtk = playerPos;
            isAttacking = true;
            Debug.Log("감지한 위치 : " + whereToAtk);
            Instantiate(warning, whereToAtk, transform.rotation);
            yield return new WaitForSeconds(2f);
            StartCoroutine("Attack");
        }
    }

    IEnumerator Attack(){
        Debug.Log("그래서 공격중임");
        Instantiate(Atk1, whereToAtk, transform.rotation);
        yield return new WaitForSeconds(1f);
        Debug.Log("공격 끝남");
        isAttacking = false;
    }
}

 

- Debug.Log를 통해서 현재 어떤 작업을 처리하고 있는지 알 수 있게 함

- BeforeAttack함수에서 바로 playerPos 변수를 사용하면 경고랑 실질적인 공격의 위치가 달라지게 된다.

    - 이는 Stay함수가 계속해서 플레이어 포지션을 받아오기 때문

 

<부족한점>

- OntriggerStay2D 함수에서 player의 위치를 저장한 뒤 공격을 처리하는 과정에서 whereToAtk변수가 굳이 필요한가 싶다.

    - 다시 생각해보니 Stay의 if 문에서 다른 bool변수를 이용해 선택적으로 Player의 포지션을 받아오면 되지 않을까 생각

    - 이렇게 하면 변수 하나 이득이기는 하나 비교 문장이 하나 더 드니 생각해봐야 할 듯

 

반응형