터치 및 입력
OnMouse와 Input, 인터페이스 등...
Unity에서 자주 사용되는 입력 처리 방법들을 정리했습니다.
마땅한 순서 기준 없이 생각의 흐름대로 정리한 거라 양해부탁드립니다.

OnMouse 계열 메서드
Collider있는 오브젝트나, GUIElement에서 작동합니다.
Raycast 기반이며 (Physics 필요 없음) PC, 모바일 모두 사용 가능합니다.
private void OnMouseDown() {
// 마우스 클릭 시작
}
private void OnMouseDrag() {
// 클릭한 상태에서 드래그 중
}
private void OnMouseUp() {
// 마우스 버튼에서 손 뗐을 때
}
Raycast + Input 조합
3D 클릭 감지 방식으로, 위의 OnMouse가 한께가 있을 때 자주 쓰이는 방식입니다.
Input.GetMouseButtonDown() + Physics.Raycast()로 직접 처리!
void Update() {
if (Input.GetMouseButtonDown(0)) {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit)) {
Debug.Log("클릭한 오브젝트 : " + hit.collider.name);
}
}
}
Input.GetMouseButton~ 계열 메서드
Input.GetMouseButton~(n) (n = 0 : LMB, 1 : RMB, 2 : MMB) 입니다.
if (Input.GetMouseButton(0)) {
// 마우스 왼쪽 버튼 누르고 있는 중
}
if (Input.GetMouseButtonDown(1)) {
// 마우스 오른쪽 버튼 누를 때
}
if (Input.GetMouseButtonUp(2)) {
// 마우스 가운데 버튼에서 손가락을 뗄 때
}
Input.mousePosition
화면에서의 마우스 좌표를 얻을 수 있습니다.
Vector3 mousePos = Input.mousePosition;
// (0,0) = 화면 왼쪽 아래
// (Screen.width, Screen.height) = 오른쪽 위
화면상의 좌표를 월드 좌표로 변환하려면,
Vector3 worldPos = Camera.main.ScreenToWorldPoint(mousePos);
Input.GetKey~ 계열
Input.GetKey~(KeyCode) 마우스 입력과 같은 방식입니다.
if (Input.GetKeyDown(KeyCode.Space)) {
Debug.Log("스페이스바 누름");
}
if (Input.GetKey(KeyCode.LeftArrow)) {
Debug.Log("왼쪽키 누르는 중");
}
if (Input.GetKeyUp(KeyCode.Escape)) {
Debug.Log("ESC에서 손 뗌");
}
Input.GetAxis / GetAxisRaw
키보드나 조이스틱 컨트롤러의 연속적인 입력을 받을 때 사용됩니다.
float horizontal = Input.GetAxis("Horizontal"); // A / D, ← / →
float vertical = Input.GetAxis("Vertical"); // W / S, ↑ / ↓
Input.anyKey / nayKeyDown
게임 맨 처음 시작시 "아무 곳이나 터치해 시작하세요." 의 기능을 구현할 때 사용할 수 있습니다.
if (Input.anyKeyDown) {
Debug.Log("아무 키가 눌림!");
}
Touch 구조체
모바일 전용, 터치 입력 시스템입니다. 멀티터치 지원이 가능하며 아래와 같이 구조체 생성 후 사용하실 수 있습니다.
- Input.touchCount로 터치 개수 확인
- Input.GetTouch(index)로 터치 접근
- TouchPhase 값
Began 터치 시작 Moved 움직이는 중 Stationary 움직이지 않음 Ended 손가락을 뗌 Canceled 시스템에 의해 취소됨
void Update() {
if (Input.touchCount > 0) {
Touch touch = Input.GetTouch(n); // n = 0 ~ 5(?), 0은 첫번째로 누른 터치
int xPos = touch.position.x; // x축 터치 위치 값이 궁금할 때
int yPos = touch.position.y; // y축 터치 위치 값이 궁금할 때
switch (touch.phase) {
case TouchPhase.Began:
Debug.Log("터치 시작");
break;
case TouchPhase.Moved:
Debug.Log("터치 상태로 움직임");
break;
case TouchPhase.Ended:
Debug.Log("터치 끝");
break;
}
}
}
💡 TouchPhase.Moved와 Touch.deltaPosition을 조합하면 드래그 방향 감지도 가능합니다.
여기까지 간단한 마우스 인풋이나 키 입력, 터치 등 정리해보았습니다.
InputSystem 패키지를 사용하면 (Key mapping, Rebinding 등) 더 정교한 입력 처리가 가능하오니,
추가로 정리하도록 하겠습니다.
그럼 오늘도 좋은 하루 되세요~ (ノ´∩。• ᵕ •。∩)ノ
'- Unity > let us all UNITE !' 카테고리의 다른 글
| [Unity] Addressable #1 (Local) (0) | 2025.06.19 |
|---|---|
| [Unity] Getting started with UniRX ( Observer Pattern ) (1) | 2025.05.22 |
| [Unity] Awake OnEnable Start (0) | 2025.05.17 |
| [Unity] Update FixedUpdate LateUpdate (0) | 2025.05.16 |
| [Unity] InputSystem 인풋시스템 (1) | 2025.04.25 |