Using KinematicBody2D

    Note

    This document assumes you’re familiar with Godot’s various physics bodies. Please read first.

    KinematicBody2D is for implementing bodies that are to be controlled via code. They 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.

    Tip

    A KinematicBody2D can be affected by gravity and other forces, but you must calculate the movement in code. The physics engine will not move a 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 will instantly stop if a collision is detected with another body. After a KinematicBody2D has collided, any collision response must be coded manually.

    Warning

    Kinematic body movement should only be done in the _physics_process() callback.

    The two movement methods serve different purposes, and later in this tutorial, you’ll see examples of how they work.

    This method takes one parameter: a Vector2 indicating the body’s relative movement. Typically, this is your velocity vector multiplied by the frame timestep (delta). If the engine detects a collision anywhere along this vector, the body will immediately stop moving. If this happens, the method will return a object.

    KinematicCollision2D is an object containing data about the collision and the colliding object. Using this data, you can calculate your collision response.

    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. This is especially useful in platformers or top-down games, for example.

    Tip

    move_and_slide() automatically calculates frame-based movement using delta. Do not multiply your velocity vector by delta before passing it to move_and_slide().

    In addition to the velocity vector, move_and_slide() takes a number of other parameters allowing you to customize the slide behavior:

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

    • slope_stop_min_velocity - default value: 5

    • max_bounces - default value: 4

    • floor_max_angle - default value: 0.785398 (in radians, equivalent to 45 degrees)

    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(0, 0) or by using move_and_slide() instead.

    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:

    GDScript

    C#

    1. // using MoveAndCollide
    2. var collision = MoveAndCollide(velocity * delta);
    3. if (collision != null)
    4. {
    5. velocity = velocity.Slide(collision.Normal);
    6. }
    7. // using MoveAndSlide
    8. velocity = MoveAndSlide(velocity);

    Anything you do with move_and_slide() can also be done with move_and_collide(), but it might take a little more code. However, as we’ll see in the examples below, there are cases where move_and_slide() doesn’t provide the response you want.

    To see these examples in action, download the sample project: using_kinematic2d.zip.

    Movement and walls

    If you’ve downloaded the sample project, this example is in “BasicMovement.tscn”.

    For this example, add a KinematicBody2D with two children: a Sprite and a CollisionShape2D. Use the Godot “icon.png” as the Sprite’s texture (drag it from the Filesystem dock to the Texture property of the Sprite). In the CollisionShape2D’s Shape property, select “New RectangleShape2D” and size the rectangle to fit over the sprite image.

    Note

    See for examples of implementing 2D movement schemes.

    Attach a script to the KinematicBody2D and add the following code:

    GDScript

    C#

    1. extends KinematicBody2D
    2. var speed = 250
    3. var velocity = Vector2()
    4. func get_input():
    5. # Detect up/down/left/right keystate and only move when pressed.
    6. velocity = Vector2()
    7. if Input.is_action_pressed('ui_right'):
    8. velocity.x += 1
    9. if Input.is_action_pressed('ui_left'):
    10. velocity.x -= 1
    11. if Input.is_action_pressed('ui_down'):
    12. velocity.y += 1
    13. if Input.is_action_pressed('ui_up'):
    14. velocity.y -= 1
    15. velocity = velocity.normalized() * speed
    16. func _physics_process(delta):
    17. get_input()
    18. move_and_collide(velocity * delta)

    Run this scene and you’ll see that move_and_collide() works as expected, moving the body along the velocity vector. Now let’s see what happens when you add some obstacles. Add a StaticBody2D with a rectangular collision shape. For visibility, you can use a sprite, a Polygon2D, or turn on “Visible Collision Shapes” from the “Debug” menu.

    Run the scene again and try moving into the obstacle. You’ll see that the KinematicBody2D can’t penetrate the obstacle. However, try moving into the obstacle at an angle and you’ll find that the obstacle acts like glue - it feels like the body gets stuck.

    This happens because there is no collision response. move_and_collide() stops the body’s movement when a collision occurs. We need to code whatever response we want from the collision.

    Try changing the function to and running again. Note that we removed delta from the velocity calculation.

    What if you don’t want a sliding collision response? For this example (“BounceandCollide.tscn” in the sample project), we have a character shooting bullets and we want the bullets to bounce off the walls.

    This example uses three scenes. The main scene contains the Player and Walls. The Bullet and Wall are separate scenes so that they can be instanced.

    The Player is controlled by the w and s keys for forward and back. Aiming uses the mouse pointer. Here is the code for the Player, using move_and_slide():

    GDScript

    C#

    1. extends KinematicBody2D
    2. var Bullet = preload("res://Bullet.tscn")
    3. var speed = 200
    4. var velocity = Vector2()
    5. func get_input():
    6. # Add these actions in Project Settings -> Input Map.
    7. velocity = Vector2()
    8. if Input.is_action_pressed('backward'):
    9. velocity = Vector2(-speed/3, 0).rotated(rotation)
    10. if Input.is_action_pressed('forward'):
    11. velocity = Vector2(speed, 0).rotated(rotation)
    12. if Input.is_action_just_pressed('mouse_click'):
    13. shoot()
    14. # "Muzzle" is a Position2D placed at the barrel of the gun.
    15. var b = Bullet.instance()
    16. b.start($Muzzle.global_position, rotation)
    17. get_parent().add_child(b)
    18. func _physics_process(delta):
    19. get_input()
    20. var dir = get_global_mouse_position() - global_position
    21. # Don't move if too close to the mouse pointer.
    22. if dir.length() > 5:
    23. rotation = dir.angle()
    24. velocity = move_and_slide(velocity)
    1. using Godot;
    2. using System;
    3. public class KBExample : KinematicBody2D
    4. {
    5. private PackedScene _bullet = (PackedScene)GD.Load("res://Bullet.tscn");
    6. public int Speed = 200;
    7. private Vector2 _velocity = new Vector2();
    8. public void GetInput()
    9. {
    10. // add these actions in Project Settings -> Input Map
    11. _velocity = new Vector2();
    12. if (Input.IsActionPressed("backward"))
    13. {
    14. _velocity = new Vector2(-speed/3, 0).Rotated(Rotation);
    15. }
    16. if (Input.IsActionPressed("forward"))
    17. {
    18. _velocity = new Vector2(speed, 0).Rotated(Rotation);
    19. }
    20. if (Input.IsActionPressed("mouse_click"))
    21. {
    22. Shoot();
    23. }
    24. }
    25. public void Shoot()
    26. {
    27. // "Muzzle" is a Position2D placed at the barrel of the gun
    28. var b = (Bullet)_bullet.Instance();
    29. b.Start(GetNode<Node2D>("Muzzle").GlobalPosition, Rotation);
    30. GetParent().AddChild(b);
    31. }
    32. public override void _PhysicsProcess(float delta)
    33. {
    34. GetInput();
    35. var dir = GetGlobalMousePosition() - GlobalPosition;
    36. // Don't move if too close to the mouse pointer
    37. if (dir.Length() > 5)
    38. {
    39. Rotation = dir.Angle();
    40. _velocity = MoveAndSlide(_velocity);
    41. }
    42. }
    43. }

    And the code for the Bullet:

    GDScript

    C#

    1. using Godot;
    2. public class Bullet : KinematicBody2D
    3. {
    4. public int Speed = 750;
    5. private Vector2 _velocity = new Vector2();
    6. public void Start(Vector2 pos, float dir)
    7. {
    8. Rotation = dir;
    9. Position = pos;
    10. _velocity = new Vector2(speed, 0).Rotated(Rotation);
    11. }
    12. public override void _PhysicsProcess(float delta)
    13. {
    14. var collsion = MoveAndCollide(_velocity * delta);
    15. if (collsion != null)
    16. {
    17. _velocity = _velocity.Bounce(collsion.Normal);
    18. if (collsion.Collider.HasMethod("Hit"))
    19. {
    20. collsion.Collider.Hit();
    21. }
    22. }
    23. }
    24. public void OnVisibilityNotifier2DScreenExited()
    25. {
    26. QueueFree();
    27. }
    28. }

    The action happens in _physics_process(). After using move_and_collide(), if a collision occurs, a KinematicCollision2D object is returned (otherwise, the return is Nil).

    If there is a returned collision, we use the normal of the collision to reflect the bullet’s velocity with the Vector2.bounce() method.

    If the colliding object (collider) has a hit method, we also call it. In the example project, we’ve added a flashing color effect to the Wall to demonstrate this.

    ../../_images/k2d_bullet_bounce.gif

    Platformer movement

    Let’s try one more popular example: the 2D platformer. move_and_slide() is ideal for quickly getting a functional character controller up and running. If you’ve downloaded the sample project, you can find this in “Platformer.tscn”.

    For this example, we’ll assume you have a level made of StaticBody2D objects. They can be any shape and size. In the sample project, we’re using to create the platform shapes.

    Here’s the code for the player body:

    GDScript

    C#

    1. extends KinematicBody2D
    2. export (int) var run_speed = 100
    3. export (int) var jump_speed = -400
    4. export (int) var gravity = 1200
    5. var velocity = Vector2()
    6. var jumping = false
    7. func get_input():
    8. velocity.x = 0
    9. var right = Input.is_action_pressed('ui_right')
    10. var left = Input.is_action_pressed('ui_left')
    11. var jump = Input.is_action_just_pressed('ui_select')
    12. if jump and is_on_floor():
    13. jumping = true
    14. velocity.y = jump_speed
    15. if right:
    16. velocity.x += run_speed
    17. if left:
    18. velocity.x -= run_speed
    19. func _physics_process(delta):
    20. get_input()
    21. velocity.y += gravity * delta
    22. if jumping and is_on_floor():
    23. jumping = false
    24. velocity = move_and_slide(velocity, Vector2(0, -1))

    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 smoothly move up and down slopes. 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 is a vector pointing straight upward. This means that if the character collides with an object that has this normal, it will be considered a floor.

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