본문 바로가기

유니티/유니티 엔진

[유니티] 오버랩 박스 (충돌 감지)

728x90
반응형

 오버랩 박스 생성

 

하나의 오브젝트에 콜라이더를 2개 이상 적용하고 싶을 수도 있다.

 

이를테면 캐릭터의 공격범위나 감지범위 등을 설정할 때 필요할 것이다.

 

그러나 콜라이더를 2개 이상 적용할 수는 없다.

 

OnCollisionEnter 함수나 OnTriggerEnter 함수가 제대로 작동하지 않을 수 있기 때문이다.

 

범위가 의도한 바와 달라진다던가 중복해서 함수가 실행된다던가 등의 문제가 발생한다.

 

 

 

그렇다면 어떻게 이를 해결해야 할까?

 

이럴 때 사용할 수 있는 것이 오버랩 박스이다.

 

2D에서 오버랩 박스를 만들기위한 코드는 다음과 같다.

 

Collider2D[] collider2Ds = Physics2D.OverlapBoxAll(Pos.position, BoxSize, 0);

 

 

 

 

 

 

OverlapBoxAll 함수는 2차원벡터 2개와 int형 정수 1개를 인수로 요구하는데

처음 벡터값은 박스의 위치, 두번째 벡터값은 박스의 크기, 3번째 정수의 값은 layer 를 의미한다.

 

따라서 Transform 변수와 Vector2 변수를 선언해 줄 필요가 있다.

 

최종 코드는 아래와 같다.

 

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

public class NewBehaviourScript : MonoBehaviour
{
    public Transform Pos;
    private Vector2 BoxSize = new Vector2(1, 1);
    // Start is called before the first frame update
    void Start()
    {
        Pos.position = new Vector2(0, 0);
    }

    // Update is called once per frame
    void Update()
    {
        Collider2D[] collider2Ds = Physics2D.OverlapBoxAll(Pos.position, BoxSize, 0);
    }
}

 

 

 

 

 

 

 

 

위와 같이 작성했다면 Pos를 public으로 작성했기때문에 Inspector 창에 Pos 라는 변수가 있을 것이다.

 

 

여기 아무런 오브젝트도 할당해주지 않았기 때문에 None 이라고 표기되어 있다.

 

이제 Hierarchy 창에서 드래그&드롭으로 오브젝트를 가져오던지 우측의 원을 눌러서 오브젝트를 할당해주면 된다.

 

 

 

 

 

 

 

 

 

 

 충돌 감지

 

오버랩 박스를 사용하여 충돌을 감지하는 코드는 다음과 같다.

 

Collider2D[] collider2Ds = Physics2D.OverlapBoxAll(AttackPos.position, AttackBoxSize, 0);
foreach (Collider2D collider in collider2Ds)
{
	if (collider.name == "Enemy")
    {
    	Debug.Log("충돌");
    }
}

 

Enemy 라는 이름의 콜라이더를 적용한 오브젝트와 충돌하면 "충돌" 이라는 메시지를 출력한다.

 

 

 

 

 

 

 최종 코드

 

 

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

public class NewBehaviourScript : MonoBehaviour
{
    public Transform Pos;
    private Vector2 BoxSize = new Vector2(1, 1);
    // Start is called before the first frame update
    void Start()
    {
        Pos.position = new Vector2(0, 0);
    }

    // Update is called once per frame
    void Update()
    {
        Collider2D[] collider2Ds = Physics2D.OverlapBoxAll(Pos.position, BoxSize, 0);
        
		foreach (Collider2D collider in collider2Ds)
		{
			if (collider.name == "Enemy")
    			Debug.Log("충돌");
		}
    }
}

 

 

 

 

 

 

 

728x90
반응형