본문 바로가기
Godot

[GodotDocs][Step by step] 4. 플레이어 입력 수신(GDScript)

by 채식금지 2023. 12. 29.
728x90

본 게시글은 고도엔진 공식문서에 작성된 Listening to player input를 정리하였습니다.

 

 

  • 고도 엔진은 2가지 방식으로 플레이어 입력을 처리한다.
    • _unhandled_input 함수를 선언한다.
      • 플레이어가 입력할 때마다 호출된다.
      • 매 프래임 마다 입력 중인지 아닌지 확인할 필요가 없는 작업에 적합하다.
    • Input 클래스 사용
      • Input 클래스를 전역으로 호출할 수 있다.
      • 매 프리임 마다 입력 중인지 아닌지 확인해야 되는 작업에 적합하다.

 

실습

var direction = 0
if Input.is_action_pressed("ui_left"):
    direction = -1
if Input.is_action_pressed("ui_right"):
    direction = 1
rotation += angular_speed * direction * delta
  • Input.is_action_pressed
    • 매 프래임 마다 매핑된 키를 누르고 있는지 안 누르고 있는지 확인할 때 사용한다.
    • 누르고 있으면 true, 안 누르고 있으면 false를 반환한다.
  • 입력 매핑
    • Project>Project Settings... 를 선택하였을 때 열리는 팝업창에서 어떤 키를 입력하였을 때 어떤 동작이 발생하게 되는지 설정할 수 있다.
    • ui_leftui_right는 프로젝트에 기본 설정된 입력 동작이다.
    • ui_left는 키보드 왼쪽 방향키, 컨트롤러 왼쪽 방향키, 컨트롤러 왼쪽 D-Pad를 왼쪽으로 옮겼을 때 동작한다.
    • ui_right는 키보드 오른쪽 방향키, 컨트롤러 오른쪽 방향키, 컨트롤러 왼쪽 D-Pad를 오른쪽으로 옮겼을 때 동작한다.
  • _process 함수 내부의 var velocity = Vector2.UP.rotated(rotation) * speed를 아래 내용으로 수정한다.
  • 아래 코드는 위쪽 방향키를 누르고 있을 때만 아이콘을 기준으로 위쪽으로 이동하도록 만들어준다.
var velocity = Vector2.ZERO
if Input.is_action_pressed("ui_up"):
    velocity = Vector2.UP.rotated(rotation) * speed
  • my_sprite_2d.gd 파일을 저장한다.
  • 오른쪽 상단의 Run Project 를 선택하여 결과를 확인한다.

 

완성된 스크립트

extends Sprite2D

var speed = 400
var angular_speed = PI

func _init():
    print("Hello, world!")

func _process(delta):
    var direction = 0
    if Input.is_action_pressed("ui_left"):
        direction = -1
    if Input.is_action_pressed("ui_right"):
        direction = 1
    rotation += angular_speed * direction * delta

    var velocity = Vector2.ZERO
    if Input.is_action_pressed("ui_up"):
        velocity = Vector2.UP.rotated(rotation) * speed
    position += velocity * delta