Using KinematicBody2D
Introduction
KinematicBody2D node and show some examples of how to use it. Note Physics introduction first.
What is a kinematic body?
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.
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.
Movement and collision
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.
Warning
_physics_process() callback.
The two movement methods serve different purposes, and later in this tutorial, you’ll see examples of how they work.
move_and_collide
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 KinematicCollision2D 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
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.
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().
move_and_slide() takes a number of other parameters allowing you to customize the slide behavior:
up_direction- default value:Vector2( 0, 0 )is_on_floor(),is_on_wall(), andis_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:falseThis parameter prevents a body from sliding down slopes when standing still.
max_slides- default value:4This parameter is the maximum number of collisions before the body stops moving. Setting it too low may prevent movement entirely.
floor_max_angle- default value:0.785398(in radians, equivalent to45degrees)This parameter is the maximum angle before a surface is no longer considered a “floor.”
infinite_inertia- default value:truetrue, the body can push RigidBody2D nodes, ignoring their mass, but won’t detect collisions with them. If it’sfalsethe body will collide with rigid bodies and stop.move_and_slide_with_snapmove_and_slide()by adding thesnapparameter. 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 settingsnaptoVector2.ZEROor by usingmove_and_slide()instead.Detecting collisions
move_and_collide()the function returns aKinematicCollision2Ddirectly, and you can use this in your code.move_and_slide()it’s possible to have multiple collisions occur, as the slide response is calculated. To process these collisions, useget_slide_count()andget_slide_collision(): GDScript C## 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)
Note get_slide_count() only counts times the body has collided and changed direction. KinematicCollision2D for details on what collision data is returned.// Using MoveAndCollide.var collision = MoveAndCollide(velocity * delta);if (collision != null){ GD.Print("I collided with ", ((Node)collision.Collider).Name);}// Using MoveAndSlide.velocity = MoveAndSlide(velocity);for (int i = 0; i < GetSlideCount(); i++){ var collision = GetSlideCollision(i); GD.Print("I collided with ", ((Node)collision.Collider).Name);}
Which movement method to use?
move_and_slide()because it’s “simpler,” but this is not necessarily the case. One way to think of it is thatmove_and_slide()is a special case, andmove_and_collide()is more general. For example, the following two code snippets result in the same collision response: GDScript C## using move_and_collidevar collision = move_and_collide(velocity * delta)if collision: velocity = velocity.slide(collision.normal)# using move_and_slidevelocity = move_and_slide(velocity)
// using MoveAndCollidevar collision = MoveAndCollide(velocity * delta);if (collision != null){ velocity = velocity.Slide(collision.Normal);}// using MoveAndSlidevelocity = MoveAndSlide(velocity);
move_and_slide()can also be done withmove_and_collide(), but it might take a little more code. However, as we’ll see in the examples below, there are cases wheremove_and_slide()doesn’t provide the response you want.move_and_slide()returns back into thevelocityvariable. 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 ourvelocityvariable, and use on the next frame.Examples
using_kinematic2d.zip.Movement and walls
If you’ve downloaded the sample project, this example is in “BasicMovement.tscn”.KinematicBody2Dwith two children: aSpriteand aCollisionShape2D. Use the Godot “icon.png” as the Sprite’s texture (drag it from the Filesystem dock to the Texture property of theSprite). In theCollisionShape2D‘s Shape property, select “New RectangleShape2D” and size the rectangle to fit over the sprite image. Note 2D movement overview for examples of implementing 2D movement schemes. Attach a script to the KinematicBody2D and add the following code: GDScript C#extends KinematicBody2Dvar speed = 250var 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() * speedfunc _physics_process(delta): get_input() move_and_collide(velocity * delta)
using Godot;using System;public class KBExample : KinematicBody2D{ public int Speed = 250; private Vector2 _velocity = new Vector2(); public void GetInput() { // Detect up/down/left/right keystate and only move when pressed _velocity = new Vector2(); if (Input.IsActionPressed("ui_right")) _velocity.x += 1; if (Input.IsActionPressed("ui_left")) _velocity.x -= 1; if (Input.IsActionPressed("ui_down")) _velocity.y += 1; if (Input.IsActionPressed("ui_up")) _velocity.y -= 1; _velocity = _velocity.Normalized() * Speed; } public override void _PhysicsProcess(float delta) { GetInput(); MoveAndCollide(_velocity * delta); }}
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.KinematicBody2Dcan’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. 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.move_and_slide(velocity)and running again. Note that we removeddeltafrom the velocity calculation.move_and_slide()provides a default collision response of sliding the body along the collision object. This is useful for a great many game types, and may be all you need to get the behavior you want.Bouncing/reflecting
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.move_and_slide(): GDScript C#extends KinematicBody2Dvar Bullet = preload("res://Bullet.tscn")var speed = 200var 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)
And the code for the Bullet: GDScript C#using Godot;using System;public class KBExample : KinematicBody2D{ private PackedScene _bullet = (PackedScene)GD.Load("res://Bullet.tscn"); public int Speed = 200; private Vector2 _velocity = new Vector2(); public void GetInput() { // add these actions in Project Settings -> Input Map _velocity = new Vector2(); if (Input.IsActionPressed("backward")) { _velocity = new Vector2(-Speed/3, 0).Rotated(Rotation); } if (Input.IsActionPressed("forward")) { _velocity = new Vector2(Speed, 0).Rotated(Rotation); } if (Input.IsActionPressed("mouse_click")) { Shoot(); } } public void Shoot() { // "Muzzle" is a Position2D placed at the barrel of the gun var b = (Bullet)_bullet.Instance(); b.Start(GetNode<Node2D>("Muzzle").GlobalPosition, Rotation); GetParent().AddChild(b); } public override void _PhysicsProcess(float delta) { GetInput(); var dir = GetGlobalMousePosition() - GlobalPosition; // Don't move if too close to the mouse pointer if (dir.Length() > 5) { Rotation = dir.Angle(); _velocity = MoveAndSlide(_velocity); } }}
extends KinematicBody2Dvar speed = 750var 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()
using Godot;using System;public class Bullet : KinematicBody2D{ public int Speed = 750; private Vector2 _velocity = new Vector2(); public void Start(Vector2 pos, float dir) { Rotation = dir; Position = pos; _velocity = new Vector2(speed, 0).Rotated(Rotation); } public override void _PhysicsProcess(float delta) { var collision = MoveAndCollide(_velocity * delta); if (collision != null) { _velocity = _velocity.Bounce(collision.Normal); if (collision.Collider.HasMethod("Hit")) { collision.Collider.Call("Hit"); } } } public void OnVisibilityNotifier2DScreenExited() { QueueFree(); }}
_physics_process(). After usingmove_and_collide(), if a collision occurs, aKinematicCollision2Dobject is returned (otherwise, the return isNil).normalof the collision to reflect the bullet’svelocitywith theVector2.bounce()method.collider) has ahitmethod, we also call it. In the example project, we’ve added a flashing color effect to the Wall to demonstrate this.Platformer movement
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”.StaticBody2Dobjects. They can be any shape and size. In the sample project, we’re using Polygon2D to create the platform shapes. Here’s the code for the player body: GDScript C#extends KinematicBody2Dexport (int) var run_speed = 100export (int) var jump_speed = -400export (int) var gravity = 1200var velocity = Vector2()var jumping = falsefunc 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_speedfunc _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))
using Godot;using System;public class KBExample : KinematicBody2D{ [Export] public int RunSpeed = 100; [Export] public int JumpSpeed = -400; [Export] public int Gravity = 1200; Vector2 velocity = new Vector2(); bool jumping = false; public void GetInput() { velocity.x = 0; bool right = Input.IsActionPressed("ui_right"); bool left = Input.IsActionPressed("ui_left"); bool jump = Input.IsActionPressed("ui_select"); if (jump && IsOnFloor()) { jumping = true; velocity.y = JumpSpeed; } if (right) velocity.x += RunSpeed; if (left) velocity.x -= RunSpeed; } public override void _PhysicsProcess(float delta) { GetInput(); velocity.y += Gravity * delta; if (jumping && IsOnFloor()) jumping = false; velocity = MoveAndSlide(velocity, new Vector2(0, -1)); }}
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’svelocityallows us to move up and down slopes smoothly. Try removingvelocity =and see what happens if you don’t do this.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.is_on_floor(). This function will only returntrueafter amove_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 settingfloor_max_angle.is_on_wall(), for example.
