Up to date

This page is up to date for Godot 4.2. If you still find outdated information, please open an issue.

Listening to player input

Building upon the previous lesson, Creating your first script, let's look at another important feature of any game: giving control to the player. To add this, we need to modify our sprite_2d.gd code.

../../_images/scripting_first_script_moving_with_input.gif

Godot에서 플레이어의 입력을 처리하는 두 가지 주요 도구가 있습니다:

  1. 내장 입력 콜백, 주로 _unhandled_input(). ``_process()``와 마찬가지로, 플레이어가 키를 누를 때마다 Godot가 호출하는 내장 가상 함수입니다. :kbd:`Space`를 눌러 점프하는 것과 같이, 매 프레임마다 발생하는 것은 아닌 이벤트에 반응하는 데 사용할 수 있는 도구입니다. 입력 콜백에 대해 자세히 알아보려면 :ref:`doc_inputevent`를 참조하세요.

  2. Input 싱글톤. 싱글톤은 전역적으로 액세스 가능한 객체입니다. Godot는 스크립트의 여러 항목에 대한 액세스를 제공합니다. 매 프레임마다 입력을 확인할 때 적합한 도구입니다.

매 프레임마다 플레이어가 회전이나 이동을 원하는지 알아야 하므로 여기서는 Input 싱글턴을 사용할 것입니다.

회전을 위해서는 새 변수 direction``를 사용해야 합니다. ``_process() 함수에서, rotation += angle_speed * 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

우리의 direction 지역 변수는 플레이어가 회전하려는 방향을 나타내는 곱하는 수입니다. '0' 값은 플레이어가 왼쪽 또는 오른쪽 화살표 키를 누르고 있지 않음을 의미합니다. '1'은 플레이어가 오른쪽, '-1'은 왼쪽으로 돌기를 원한다는 의미입니다.

이러한 값을 생성하기 위해, 조건문과 Input 사용을 소개합니다. 조건문은 GDScript에서 if 키워드로 시작하고 콜론으로 끝납니다. 조건은 키워드와 줄 끝 사이의 표현식입니다.

현재 프레임에서 키가 눌렸는지 확인하기 위해 ``Input.is_action_pressed()``를 호출합니다. 이 메서드는 입력 동작을 나타내는 텍스트 문자열을 가져와 해당 동작이 눌려지면 'true'를 반환하고, 그렇지 않으면 'false'를 반환합니다.

위에서 사용한 "ui_left"와 "ui_right"는 모든 Godot 프로젝트에 미리 정의되어 있습니다. 플레이어가 키보드의 왼쪽 및 오른쪽 화살표를 누르거나 게임 패드의 D 패드에서 왼쪽 및 오른쪽 화살표를 누를 때 각각 트리거됩니다.

참고

프로젝트 -> 프로젝트 설정으로 이동하여 입력 맵 탭을 클릭하면 프로젝트의 입력 작업을 보고 편집할 수 있습니다.

마지막으로 direction``을 곱해서 노드의 ``roatation``을 갱신합니다: ``rotation += angular_speed * direction * delta.

이 코드로 씬을 실행하면 Left 및 :kbd:`Right`를 누를 때 아이콘이 회전해야 합니다.

"up"을 눌러 이동하기

키를 누를 때만 이동하려면, 속도를 계산하는 코드를 수정해야 합니다. ``var Velocity``로 시작하는 줄을 아래 코드로 바꿉니다.

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

velocity``은 ``Vector2.ZERO``로 초기화 한다. 여기서 ``Vector 타입의 내장 상수 ``Vector2.ZERO``은 길이가 0인 벡터를 의미한다.

플레이어가 "ui_up" 액션을 누르면, 속도값을 변경해 스프라이트가 앞으로 이동하게 한다.

Complete script

Here is the complete sprite_2d.gd file for reference.

extends Sprite2D

var speed = 400
var angular_speed = PI


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

이제 씬을 실행하면 왼쪽 및 오른쪽 화살표 키로 회전하고 :kbd:`Up`을 눌러 앞으로 이동할 수 있어야 합니다.

../../_images/scripting_first_script_moving_with_input.gif

요약

In summary, every script in Godot represents a class and extends one of the engine's built-in classes. The node types your classes inherit from give you access to properties, such as rotation and position in our sprite's case. You also inherit many functions, which we didn't get to use in this example.

GDScript에서 파일 맨 위에 넣는 변수는 클래스의 프로퍼티이며 멤버 변수라고도 합니다. 변수 외에도 함수를 정의할 수 있는데, 대부분의 경우 클래스의 메서드가 될 것입니다.

Godot은 클래스와 엔진을 연결하기 위해 여러분이 정의할 수 있는 몇 가지 가상 함수를 제공합니다. 여기에는 매 프레임마다 노드에 변경 사항을 적용하는 _process() 와 사용자로부터 키 및 버튼 누름과 같은 입력 이벤트를 수신하는 _unhandled_input() 이 포함됩니다. 이 외에도 꽤 많은 함수가 있습니다.

Input 싱글톤을 사용하면 코드의 어느 곳에서나 플레이어의 입력에 반응할 수 있습니다. 특히 _process() 루프에서 이것을 사용하게 될 것입니다.

In the next lesson, Using signals, we'll build upon the relationship between scripts and nodes by having our nodes trigger code in scripts.