Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

codingfarm

Ray와 Raycast충돌 본문

Unity5/기타

Ray와 Raycast충돌

scarecrow1992 2020. 6. 5. 13:41

 

Raycast란 무엇일까?

원하는 좌표에서 설정된 방향으로 설정된 거리이내에 충돌체가 있는지 없는지 충돌감지에 주로 쓰입니다.

플레이어의 오른쪽으로 ray가 뻗어 나옴이 육안으로 확인 되며

ray에 닿는순간 붉은색으로 변한 모습입니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class RayTest2 : MonoBehaviour
{
    RaycastHit hit;
    // Start is called before the first frame update
    void Start()
    {
        
    }
 
    // Update is called once per frame
    void Update()
    {
        Debug.DrawRay(transform.position + new Vector3(0.5f, 0.5f, 0), Vector3.right * 2.5f, Color.red);
        
        if(Physics.Raycast(transform.position + new Vector3(0.5f, 0.5f,0), Vector3.right, out hit, 2.5f)) {
            hit.transform.GetComponent<Renderer>().material.color = Color.red;
        }
    }
}
 
cs
1
public static bool Raycast(Vector3 origin, Vector3 direction, float maxDistance = Mathf.Infinity, int layerMask = DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal);
cs

 

만약 "Enemy" LayerMask만을 가진 오브젝트와 충돌을 허용하게끔 설정하고 싶다면 아래와 같이 설정합니다.

ray와의 충돌을 원하는 오브젝트의 Layer를 Enemy로 설정합니다.

여기서 Enemy가 8번 layer임을 확인합니다.

코드를 아래와 같이 수정해줍니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class RayTest2 : MonoBehaviour
{
    RaycastHit hit;
    int layerMask = 1 << 8;
    // Start is called before the first frame update
    void Start()
    {
        
    }
 
    // Update is called once per frame
    void Update()
    {
        Debug.DrawRay(transform.position + new Vector3(0.5f, 0.5f, 0), Vector3.right * 2.5f, Color.red);
        
        if(Physics.Raycast(transform.position + new Vector3(0.5f, 0.5f,0), Vector3.right * 2.5f, out hit, 2.5f, layerMask)) {
            hit.transform.GetComponent<Renderer>().material.color = Color.red;
        }
    }
}
 
cs

layer는 0~31번까지 최대 32개 까지 허용하며 bitMask의 형태로 사용합니다.

그러므로 int자료형으로 마스크를 선언해준후에 충돌을 허용하는 layer의 번호에 한해서만 bit를 1로 설정합니다.

이제 3개의 오브젝트에 모두다 ray를 충돌시키더라도 Enemy로 설정된 2개의 오브젝트만 붉은색으로 변했음이 확인됩니다.

 

ray는 자신이 감지 가능한 오브젝트와 부딪히는 순간 바로 정지되며

다른 collider가 있을지라도 감지가 불가능하다면 무시하고 꿰뚫고 지나가서 뒤에 있는 object까지 감지를 진행합니다.

5개의 오브젝트 중에 enemy layer를 가지지 않은 오브젝트는 중앙의 것 하나뿐입니다.

2번째 줄에서는enemy가 아닌 오브젝트를 무시하고 뒤에 있는 enemy에 ray가 닿는 모습을 보입니다.

3번째 줄에서는 앞에 있는 enemy에 가로막혀서 뒤에 있는 enemy가 ray에 감지되지 못한 모습을 보입니다.

 

 

'Unity5 > 기타' 카테고리의 다른 글

3. 2d 플랫포머 - 캐릭터 이동  (0) 2020.07.26
코루틴  (0) 2020.06.06
mechanim(2d)  (0) 2020.06.05
오브젝트 이동하기  (0) 2020.06.05
sprite 변경하기  (0) 2020.06.05
Comments