Hya 개발스토리
[유니티 2022.3.ver] 스크립트에서 키보드 조작키 접근 방법(GetAxis(), GetButton(), GetKey()) 본문
[유니티 2022.3.ver] 스크립트에서 키보드 조작키 접근 방법(GetAxis(), GetButton(), GetKey())
Hya68 2024. 7. 5. 11:58스크립트에서 키보드 조작키 접근하는 방법
목차
GetAxis(), GetButton(), GetKey()
키보드 조작키 접근 방법으로는 크게
Input 클래스의 GetAxis(), GetButton(), GetKey()로 3가지가 있습니다.
(Input 클래스 : 사용자 입력 메서드를 모아둔 클래스)
GetAxis()는 결과값을 실수 타입(float)으로 반환하고
나머지 GetButton()과 GetKey()는 논리 타입(bool)으로 반환합니다.
GetAxis()의 매개변수에는 속성 이름으로 적고,
GetButton()과 GetKey()의 매개변수에는 KeyCode로 접근하거나 키 이름으로 적습니다.
GetAxis() 값 확인
GetAxis()는 -1~1 사이의 실수를 반환합니다.
오른쪽 로그 사진은 방향키 위 버튼, 아래 버튼을 차례로 누른 결과입니다.
위 버튼(양의 방향 버튼)을 누르면 0보다 크고 1보다 작은 값을 반환합니다.
아래 버튼(음의 방향 버튼)을 누르면 -1보다 크고 0보다 작은 값을 반환합니다.
버튼을 누르지 않으면 0을 반환합니다.
GetAxisAraw()는 GetAxis()와 같은 기능이지만 반환값이 -1, 0, 1로 고정되어 있습니다.
GetButton(), GetButtonDown(), GetButtonUp() 차이
GetButton()은 해당 버튼을 누르고 있는 동안 true를 반환합니다.
GetButtonDown()은 해당 버튼을 눌렀을 때 true를 반환합니다.
GetButtonUp()은 해당 버튼을 떼었을 때 true를 반환합니다.
이는 GetKey(), GetKeyDown(), GetKeyUp()에도 동일하게 적용됩니다.
그러면 아래에서는 왜 GetButtonUP()과 GetKeyUp()이 False일까요.
그 이유는 위의 조건문 때문입니다.
해당 조건문은 버튼을 누른 상태가 전제가 되어야 로그값이 나오는데
-Up() 메서드 같은 경우에는 떼어야 true가 반환됩니다.
따라서 버튼은 뗀 순간 조건문이 적용이 되지 않기 때문에
true인 -Up() 메서드는 로그에 출력되지 않습니다.
KeyCode
KeyCode는 GetKey()의 매개변수로 사용할 수 있는 실제 키 메서드입니다.
오른쪽 사진처럼 실제 KeyCode 메서드를 보면 각 변수가 정수로 초기화되어 있습니다.
따라서 KeyCode 변수는 int 타입으로
GetAxis()나 GetButton()의 매개변수로는 사용할 수 없습니다.
많이 사용하는 방향키는 UpArrow, DownArrow, RightArrow, LeftArrow이며
일반 w, a, s, d 키는 그대로 W, A, S, D 입니다.
더 많은 KeyCode 종류는 아래 링크를 확인해주세요.
https://docs.unity3d.com/kr/2022.3/ScriptReference/KeyCode.html
근데 실제로 개발을 하다 보면
키보드를 한 번 눌렀는데 콘솔창에 나타나는
GetAxis(), GetButton(), GetKey() 로그는 여러 개가 나옵니다.
그 이유는 컴퓨터의 작업 처리는 사람의 속도보다 훨씬 빠르기 때문입니다.
우리는 한 번 누른 것 같지만 컴퓨터는 그 잠깐 눌렀다 뗀 시간 동안에도
버튼을 누른 상태로 인식하여 처리하기 때문에
누르고 있는 동안 출력되는 로그는 생각하는 것보다 여러 번 나오게 됩니다.
총정리
아래는 위의 내용들을 정리한 표입니다.
메서드 | 매개변수 (매개변수타입) |
반환타입 | 반환값 |
GetAxis() | 축 이름 (string) |
float | -1 < 실수 < 0 : 속성의 음의 방향 버튼 0 : 아무것도 누르지 않음 0 < 실수 < 1 : 속성의 양의 방향 버튼 |
GetAxisRaw() | -1 : 속성의 음의 방향 버튼 0 : 아무것도 누르지 않음 1 : 속성의 양의 방향 버튼 |
||
GetButton() | bool | True : 해당 버튼을 누르고 있음 False : 해당 버튼을 누르고 있지 않음 |
|
GetButtonDown() | True : 해당 버튼을 눌렀음 False : 해당 버튼을 누르지 않았음 |
||
GetButtonUp() | True : 해당 버튼을 떼었음 False : 해당 버튼을 떼지 않았음 |
||
GetKey() | 실제 키 이름 / KeyCode 변수 (string / int) |
bool | True : 해당 버튼을 누르고 있음 False : 해당 버튼을 누르고 있지 않음 |
GetKeyDown() | True : 해당 버튼을 눌렀음 False : 해당 버튼을 누르지 않았음 |
||
GetKeyUp() | True : 해당 버튼을 떼었음 False : 해당 버튼을 떼지 않았음 |
이외의 조이스틱, 마우스 등을 다루는 함수는 아래 공식 링크를 확인해주세요.
잘못된 정보가 있으면 댓글로 피드백 부탁드립니다.
감사합니다:)
'Unity > 개념정리' 카테고리의 다른 글
[유니티 2022.3.ver] Collider 2D (0) | 2024.07.18 |
---|---|
[유니티 2022.3.ver] Rigidbody2D (3) | 2024.07.16 |
[유니티 2022.3.ver] 유니티 폴더 구조 및 역할 (0) | 2024.07.10 |
[유니티 2022.3.ver] PC 키보드 조작 설정 (입력 관리자 설정) (0) | 2024.07.04 |