使用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。
Movement and collision
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.
The two movement methods serve different purposes, and later in this tutorial, you’ll see examples of how they work.
move_and_collide
这个方法有一个 Vector2 参数以表示物体的相对运动。 通常,这是您的速度向量乘以帧时间步长( delta
)。 如果在沿着此向量方向的任何位置,引擎检测到碰撞,则物体将立即停止移动。 如果发生这种情况,该方法将返回 KinematicCollision2D 对象。
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. It is especially useful in platformers or top-down games, for example.
小技巧
move_and_slide()
使用 delta
自动计算基于帧的运动。 在将速度向量传递给 move_and_slide()
之前,请 不要 将速度向量乘以 delta
。
除了速度向量之外,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()
, 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: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
度)这是表面不再被视为“地板”之前的最大角度。
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.
Detecting collisions
When using move_and_collide()
the function returns a KinematicCollision2D
directly, and you can use this in your code.
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()
:
GDScript
# 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:
GDScript
C#
# 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)
// using MoveAndCollide
var collision = MoveAndCollide(velocity * delta);
if (collision != null)
{
velocity = velocity.Slide(collision.Normal);
}
// using MoveAndSlide
velocity = MoveAndSlide(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
。
移动和墙壁
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.
注解
有关实现2D移动方案的示例,请参阅 2D运动概述 。
将脚本附加到KinematicBody2D并添加以下代码:
GDScript
C#
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)
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;
}
public override void _PhysicsProcess(float delta)
{
GetInput();
MoveAndCollide(_velocity * delta);
}
}
运行这个场景,您会看到 move_and_collide()
按预期工作,沿着速度向量方向移动物体。 现在让我们看看当您添加一些障碍时会发生什么。 添加一个具有矩形碰撞形状的 StaticBody2D 。 为了可见性,您可以使用精灵,Polygon2D,或从“调试”菜单中打开“可见碰撞形状”。
再次运行场景并尝试移动到障碍物中。 您会看到 KinematicBody2D
无法穿透障碍物。 但是,尝试以某个角度进入障碍物,您会发现障碍物就像胶水一样 - 感觉物体被卡住了。
发生这种情况是因为没有 碰撞响应 。 ``move_and_collide()``在碰撞发生时停止物体的运动。 我们需要编写我们想要的碰撞响应。
尝试将函数更改为 move_and_slide(velocity)
并再次运行。 请注意,我们从速度计算中删除了“delta”。
``move_and_slide()``提供了一个沿碰撞对象滑动物体的默认碰撞响应。 这对于许多游戏类型都很有用,并且可能是获得所需行为所需的全部内容。
弹跳/反射
如果您不想要滑动碰撞响应怎么办? 对于这个示例(示例项目中的“BounceandCollide.tscn”),我们有一个角色射击子弹,我们希望子弹从墙上反弹。
此示例使用三个场景。 主场景包含游戏角色和墙壁。 子弹和墙是单独的场景,以便它们可以实例化。
游戏角色由’w`和`s`键控制前进和后退。 瞄准使用鼠标指针。 这是游戏角色的代码,使用``move_and_slide()``:
GDScript
C#
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)
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);
}
}
}
子弹的代码:
GDScript
C#
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()
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();
}
}
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
).
如果有一个返回的碰撞,我们使用碰撞的 normal
来反映子弹的 velocity
和 Vector2.bounce()
方法。
如果碰撞对象( collider
)有一个 hit
方法,我们也调用它。 在示例项目中,我们为墙壁添加了一个颜色闪烁效果来演示这一点。
平台运动
让我们尝试一个更流行的示例:2D平台游戏。 ``move_and_slide()``非常适合快速启动和运行功能字符控制器。 如果您已下载示例项目,可以在“Platformer.tscn”中找到它。
对于这个示例,我们假设您有一个由 StaticBody2D
对象构成的级别。 它们可以是任何形状和大小。 在示例项目中,我们使用 Polygon2D 来创建平台形状。
这是游戏角色物体的代码:
GDScript
C#
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))
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));
}
}
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.