KinematicBody2D 사용하기

소개

Godot offers several collision objects to provide both collision detection and response. Trying to decide which one to use for your project can be confusing. You can avoid problems and simplify development if you understand how each of them works and what their pros and cons are. In this tutorial, we'll look at the KinematicBody2D node and show some examples of how to use it.

참고

이 문서는 당신이 Godot의 다양한 물리 바디에 대해 잘 알고 있다고 가정합니다. 먼저 물리 소개를 읽어주세요.

키네마틱 바디란 무엇인가?

KinematicBody2D is for implementing bodies that are controlled via code. Kinematic bodies detect collisions with other bodies when moving, but are not affected by engine physics properties, like gravity or friction. While this means that you have to write some code to create their behavior, it also means you have more precise control over how they move and react.

KinematicBody2D는 중력과 다른 힘에 의해 영향을 받을 수 있지만 코드로 움직임을 계산해야 합니다. 물리 엔진이 KinematicBody2D를 움직이게 하진 않습니다.

이동과 콜리전

When moving a KinematicBody2D, you should not set its position property directly. Instead, you use the move_and_collide() or move_and_slide() methods. These methods move the body along a given vector and instantly stop if a collision is detected with another body. After a KinematicBody2D has collided, any collision response must be coded manually.

경고

You should only do Kinematic body movement in the _physics_process() callback.

두 개의 이동 메서드는 다른 목적을 지닙니다, 그리고 이 튜토리얼 이후에, 어떻게 작동하는 지에 대한 예제를 볼 것입니다.

move_and_collide

이 메서드는 하나의 매개 변수를 가집니다: 바디의 상대적인 움직임을 나타내는 Vector2입니다. 일반적으로, 이것은 속도 벡터에 프레임 타임 스텝 (delta)을 곱한 것입니다. 엔진이 이 벡터를 따라 어느 곳이든 콜리전을 감지하면, 바디는 즉시 이동을 멈춥니다. 이 경우, 메서드는 KinematicCollision2D 오브젝트를 반환합니다.

KinematicCollision2D는 콜리전과 충돌하는 오브젝트에 대한 정보를 담고 있는 오브젝트입니다. 이 정보로, 콜리전 반응을 계산할 수 있습니다.

move_and_slide

The move_and_slide() method is intended to simplify the collision response in the common case where you want one body to slide along the other. It is especially useful in platformers or top-down games, for example.

move_and_slide()delta를 사용하여 프레임 기반 이동을 자동으로 계산합니다. deltamove_and_slide()에 전달하기 전에 속도 벡터를 곱하면 안됩니다.

속도 벡터 뿐만 아니라, move_and_slide()는 많은 다른 매개변수를 가지고 있어서 슬라이드 행동을 커스터마이징 할 수 있습니다:

  • up_direction - default value: Vector2( 0, 0 )

    This parameter allows you to define what surfaces the engine should consider being the floor. Setting this lets you use the is_on_floor(), is_on_wall(), and is_on_ceiling() methods to detect what type of surface the body is in contact with. The default value means that all surfaces are considered walls.

  • stop_on_slope - default value: false

    This parameter prevents a body from sliding down slopes when standing still.

  • max_slides - default value: 4

    This parameter is the maximum number of collisions before the body stops moving. Setting it too low may prevent movement entirely.

  • floor_max_angle - 기본 값: 0.785398 (라디안에서는, 45도와 같습니다)

    This parameter is the maximum angle before a surface is no longer considered a "floor."

  • infinite_inertia - default value: true

When this parameter is true, the body can push RigidBody2D nodes, ignoring their mass, but won't detect collisions with them. If it's false the body will collide with rigid bodies and stop.

move_and_slide_with_snap

This method adds some additional functionality to move_and_slide() by adding the snap parameter. As long as this vector is in contact with the ground, the body will remain attached to the surface. Note that this means you must disable snapping when jumping, for example. You can do this either by setting snap to Vector2.ZERO or by using move_and_slide() instead.

콜리전 감지하기

move_and_collide()를 사용할 때 함수는 KinematicCollision2D를 직접 반환하고, 이 정보를 여러분의 코드에 사용할 수 있습니다.

When using move_and_slide() it's possible to have multiple collisions occur, as the slide response is calculated. To process these collisions, use get_slide_count() and get_slide_collision():

# Using move_and_collide.
var collision = move_and_collide(velocity * delta)
if collision:
    print("I collided with ", collision.collider.name)

# Using move_and_slide.
velocity = move_and_slide(velocity)
for i in get_slide_count():
    var collision = get_slide_collision(i)
    print("I collided with ", collision.collider.name)

참고

get_slide_count() only counts times the body has collided and changed direction.

See KinematicCollision2D for details on what collision data is returned.

어떤 이동 메서드를 사용해야 할까요?

A common question from new Godot users is: "How do you decide which movement function to use?" Often, the response is to use move_and_slide() because it's "simpler," but this is not necessarily the case. One way to think of it is that move_and_slide() is a special case, and move_and_collide() is more general. For example, the following two code snippets result in the same collision response:

../../_images/k2d_compare.gif
# using move_and_collide
var collision = move_and_collide(velocity * delta)
if collision:
    velocity = velocity.slide(collision.normal)

# using move_and_slide
velocity = move_and_slide(velocity)

move_and_slide()로 하는 것을 move_and_collide()또한 할 수 있습니다, 하지만 좀 더 많은 코드를 갖습니다. 하지만 아래에서 예제를 보면, move_and_slide()가 원하는 응답을 제공하지 않는 경우도 있습니다.

In the example above, we assign the velocity that move_and_slide() returns back into the velocity variable. This is because when the character collides with the environment, the function recalculates the speed internally to reflect the slowdown.

For example, if your character fell on the floor, you don't want it to accumulate vertical speed due to the effect of gravity. Instead, you want its vertical speed to reset to zero.

move_and_slide() may also recalculate the kinematic body's velocity several times in a loop as, to produce a smooth motion, it moves the character and collides up to five times by default. At the end of the process, the function returns the character's new velocity that we can store in our velocity variable, and use on the next frame.

예제

실제 예제를 보기 위해, 샘플 프로젝트를 다운로드 하세요: using_kinematic2d.zip.

이동과 벽

샘플 프로젝트를 다운로드 했다면, 이 예제는 "BasicMovement.tscn"입니다.

이 예시에서 KinematicBody2D를 두 자손과 함께 추가합니다: SpriteCollisionShape2D입니다. Godot "icon.png"를 Sprite의 텍스처 속성으로 사용합니다 (파일 시스템 독에서 SpriteTexture 속성으로 끌어다 놓으십시오). CollisionShape2DShape 속성에서 "New RectangleShape2D"를 선택하고 스프라이트 이미지에 맞게 사각형 크기를 조정합니다.

참고

2D 이동 구조를 구현하는 예제는 2D 이동 개요를 참고하세요.

KinematicBody2D에 스크립트를 붙이고 다음의 코드를 추가하세요:

extends KinematicBody2D

var speed = 250
var velocity = Vector2()

func get_input():
    # Detect up/down/left/right keystate and only move when pressed.
    velocity = Vector2()
    if Input.is_action_pressed('ui_right'):
        velocity.x += 1
    if Input.is_action_pressed('ui_left'):
        velocity.x -= 1
    if Input.is_action_pressed('ui_down'):
        velocity.y += 1
    if Input.is_action_pressed('ui_up'):
        velocity.y -= 1
    velocity = velocity.normalized() * speed

func _physics_process(delta):
    get_input()
    move_and_collide(velocity * delta)

이 씬을 실행하고 move_and_collide()가 예상대로, 바디가 속도 벡터를 따라 움직이는 것을 볼 수 있습니다. 이제 장애물을 추가하면 어떻게 되는지 봅시다. 직사각형 콜리전 모양을 가진 StaticBody2D를 추가합니다. 가시성을 위해, 스프라이트, Polygon2D, 혹은 "디버그" 메뉴에서 "콜리전 모양 보이기"를 키면 됩니다.

씬을 다시 실행하고 장애물로 움직여 봅니다. KinematicBody2D가 장애물을 통과하지 못하는 것을 볼 수 있습니다. 하지만 장애물 안으로 움직이려고 하면 장애물이 풀처럼 행동하는 것을 찾을 수 있습니다 - 바디가 끼어있는 느낌이 듭니다.

이것은 콜리전 응답이 없기 때문에 발생한 것입니다. move_and_collide()는 콜리전이 발생할 때 바디의 움직임을 멈춥니다. 콜리전로부터 원하는 어떤 응답이라도 코딩해야 합니다.

함수를 move_and_slide(velocity)로 변경하고 다시 실행합니다. 우리는 속도 계산에서 delta를 제거했습니다.

move_and_slide()는 다비가 콜리전 오브젝트를 따라 미끄러지는 기본 콜리전 응답을 제공합니다. 이것은 아주 많은 게임 유형에 유용하고, 원하는 행동을 얻을 때 필요할 수도 있습니다.

튕김/반사

미끄러지는 콜리전 응답을 원하지 않으면 어떻게 해야 할까요? (샘플 프로젝트에 있는 "BounceandCollide.tscn") 이 예제의 경우, 총을 쏘는 캐릭터가 있고 총알이 벽에 튕겨 나가게 하고 싶습니다.

이 예제는 세 개의 씬을 사용합니다. 메인 씬은 Player와 Wall을 갖고 있습니다. Bullet과 Wall은 분리된 씬으로 그들은 인스턴스 할 수 있습니다.

Player는 ws키로 조작하며 각각 앞뒤로 움직입니다. 마우스로 조준합니다. 이것이 move_and_slide()를 사용하는 Player 코드입니다:

extends KinematicBody2D

var Bullet = preload("res://Bullet.tscn")
var speed = 200
var velocity = Vector2()

func get_input():
    # Add these actions in Project Settings -> Input Map.
    velocity = Vector2()
    if Input.is_action_pressed('backward'):
        velocity = Vector2(-speed/3, 0).rotated(rotation)
    if Input.is_action_pressed('forward'):
        velocity = Vector2(speed, 0).rotated(rotation)
    if Input.is_action_just_pressed('mouse_click'):
        shoot()

func shoot():
    # "Muzzle" is a Position2D placed at the barrel of the gun.
    var b = Bullet.instance()
    b.start($Muzzle.global_position, rotation)
    get_parent().add_child(b)

func _physics_process(delta):
    get_input()
    var dir = get_global_mouse_position() - global_position
    # Don't move if too close to the mouse pointer.
    if dir.length() > 5:
        rotation = dir.angle()
        velocity = move_and_slide(velocity)

그리고 Bullet을 위한 코드입니다:

extends KinematicBody2D

var speed = 750
var velocity = Vector2()

func start(pos, dir):
    rotation = dir
    position = pos
    velocity = Vector2(speed, 0).rotated(rotation)

func _physics_process(delta):
    var collision = move_and_collide(velocity * delta)
    if collision:
        velocity = velocity.bounce(collision.normal)
        if collision.collider.has_method("hit"):
            collision.collider.hit()

func _on_VisibilityNotifier2D_screen_exited():
    queue_free()

동작은 _physics_process()에서 발생합니다. move_and_collide()를 사용한 이후, 콜리전이 발생하면, KinematicCollision2D 오브젝트는 반환됩니다 (그렇지 않으면, Nil을 반환합니다).

반환된 콜리전이 있다면, 우리는 콜리전의 normal을 사용해 Vector2.bounce() 메서드로 총알의 velocity를 반사합니다.

충돌 오브젝트 (collider)가 hit 메서드를 가진다면, 또한 그것을 호출합니다. 예제 프로젝트에서는, 이를 설명하기 위해 Wall에 반짝이는 색상 효과를 추가했습니다.

../../_images/k2d_bullet_bounce.gif

플랫포머 움직임

인기있는 예제를 하나 더 들어보겠습니다: 2D 플랫포머 입니다. move_and_slide()가 빠르게 기능의 캐릭터 조작을 얻고 실행시키기에 이상적입니다. 샘플 프로젝트를 다운로드 했다면, "Platformer.tscn"에서 이것을 찾을 수 있습니다.

이 예제를 위해,.``StaticBody2D`` 오브젝트로 만들어진 레벨이 있다고 가정합니다. 어떤 모양이나 크기가 될 수 있습니다. 샘플 프로젝트에서, 우리는 플랫폼 모양을 만들기 위해 Polygon2D를 사용합니다.

플레이어 바디를 위한 코드입니다:

extends KinematicBody2D

export (int) var run_speed = 100
export (int) var jump_speed = -400
export (int) var gravity = 1200

var velocity = Vector2()
var jumping = false

func get_input():
    velocity.x = 0
    var right = Input.is_action_pressed('ui_right')
    var left = Input.is_action_pressed('ui_left')
    var jump = Input.is_action_just_pressed('ui_select')

    if jump and is_on_floor():
        jumping = true
        velocity.y = jump_speed
    if right:
        velocity.x += run_speed
    if left:
        velocity.x -= run_speed

func _physics_process(delta):
    get_input()
    velocity.y += gravity * delta
    if jumping and is_on_floor():
        jumping = false
    velocity = move_and_slide(velocity, Vector2(0, -1))
../../_images/k2d_platform.gif

When using move_and_slide(), the function returns a vector representing the movement that remained after the slide collision occurred. Setting that value back to the character's velocity allows us to move up and down slopes smoothly. Try removing velocity = and see what happens if you don't do this.

Also note that we've added Vector2(0, -1) as the floor normal. This vector points straight upward. As a result, if the character collides with an object that has this normal, it will be considered a floor.

Using the floor normal allows us to make jumping work, using is_on_floor(). This function will only return true after a move_and_slide() collision where the colliding body's normal is within 45 degrees of the given floor vector. You can control the maximum angle by setting floor_max_angle.

This angle also allows you to implement other features like wall jumps using is_on_wall(), for example.