Unity - Rigidbody와 Collider를 이용해 충돌처리

리지드바디(Rigidbody) 기능 설명

콜라이더(Collider) 충돌 이벤트 함수


연습목표 : 플레이어가 이동할 때 벽에 충돌되면 플레이어의 색을 변하게 한자.


1. 지형, 장애물 만들기 - 태그와 레이어 설정

1 - 1 지형 만들기

큐브를 생성.


원하는 이름으로 변경하고 크기(Scale)를 적당하게 키워줍니다.


그라운드의 색상을 변경하기 위해 머티리얼이 필요함.

1. Project에 우클릭 Create에 Material을 생성한다.

2. Ground에 Mesh Renderer Matrials에 넣어준다.

3. Material에 Albedo를 설정해서 색을 변경한다.


1 - 2. 장애물 만들기

그라운드 생성과 방법은 같다.

큐르를 생성 후 그라운드보다 y값을 1높게 해서 배치해보자.

머티리얼도 하나 더 만들어 알아보기 좋게 색을 변경하자.


1 - 3 태그와 레이어 설정

Add Layer를 누르면 등록된 Layer들을 보여준다.


Ground, Player 레이어를 추가해주자.


Ground 오브젝트를 선택해 추가한 Ground 레이어로 변경하자.

Player도 레이어를 적용하자.


충돌 처리비용을 줄이기 위해서 Physics를 설정하자.


그림과 같이 그라운드와 플레이어를 충돌하지 않게 수정하자.


2. Player 오브젝트 만들기, Player 스크립트 제작

2 - 1 Player 오브젝트 만들기

빈 게임 오브젝트를 생성한다.

게임 오브젝트의 이름을 Player로 변경.


게임 오브젝트를 선택하고 우클릭해서 생성하면 Cube가 게임 오브젝트의 자식으로 생성된다.


Porjcet뷰에 스크립트를 모아둘 폴트를 만들고, Player가 사용할 스크립트를 만들자.


만들었으면 Hierarchy에 Player를 선택 후 Add Component를 이용해 스크립트를 적용하자.


Rigidbody를 AddComponent해주자.


Position에서 y값은 사용하지 않을 거라 y체크

Rotation에서 충돌 후 물리적인 회전을 사용하지 않기 위해 전부 체크.


2 - 2 Player 스크립트 작성하기

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Player : MonoBehaviour {
    Player player;
    Material material;
    Color baseColor;
    public float speed = 5;
 
    void Awake()
    {
        player = GetComponent<Player>();
        material = player.GetComponentInChildren<MeshRenderer>().material;
        baseColor = material.color;
 
    }
 
    void Update()
    {
        Vector3 dir = Vector3.zero;
        if (Input.GetKey(KeyCode.UpArrow)) {
            dir = Vector3.forward;
        }
 
        if (Input.GetKey(KeyCode.DownArrow)) {
            dir = Vector3.back;
        }
 
        if (Input.GetKey(KeyCode.RightArrow)) {
            transform.Rotate(Vector3.up);
        }
 
        if (Input.GetKey(KeyCode.LeftArrow)) {
            transform.Rotate(Vector3.down);
        }
 
        transform.Translate(dir * speed * Time.deltaTime);
    }
 
    void OnCollisionEnter(Collision collision)
    {
        // Wall일 경우 색을 변경
        material.color = Color.yellow;
    }
 
    void OnCollisionExit(Collision collision)
    {
        // Wall일 경우 색을 변경
        material.color = baseColor;
    }
}
 
cs


테스트

Unity 충돌처리(Rigidbody와 Collider).unitypackage


반응형