2D运动概述

简介

每个初学者都会说:“我如何移动我的游戏角色呢?” 根据你正在制作的游戏的风格,可能有特殊的需求,但一般来说,大多数2D游戏的运动都基于一组不太多的操作之上。

在这些示例中,我们将使用 KinematicBody2D ,但这些原则也适用于其他节点类型(Area2D,RigidBody2D)。

场景布置

以下每个示例都使用相同的场景布置。 从带有 SpriteCollisionShape2D 两个子节点的 KinematicBody2D 开始。 你可以使用Godot图标(“icon.png”)作为Sprite的纹理或使用其他任何2D图像。

打开 Project -> Project Settings 并选择 “Input Map” 选项卡。 添加以下输入操作(相关详细信息,请参阅 InputEvent ):

../../_images/movement_inputs.png

8向移动

在这种情况下,您希望用户按下四个方向键(上/左/下/右或W / A / S / D)并沿所选方向移动。 “8向移动”意味着游戏角色可以通过同时按下两个键实现斜向移动。

../../_images/movement_8way.gif

将脚本添加到场景中的KinematicBody2D上,并添加以下代码:

GDScript

C#

  1. extends KinematicBody2D
  2. export (int) var speed = 200
  3. var velocity = Vector2()
  4. func get_input():
  5. velocity = Vector2()
  6. if Input.is_action_pressed('right'):
  7. velocity.x += 1
  8. if Input.is_action_pressed('left'):
  9. velocity.x -= 1
  10. if Input.is_action_pressed('down'):
  11. velocity.y += 1
  12. if Input.is_action_pressed('up'):
  13. velocity.y -= 1
  14. velocity = velocity.normalized() * speed
  15. func _physics_process(delta):
  16. get_input()
  17. velocity = move_and_slide(velocity)
  1. using Godot;
  2. using System;
  3. public class Movement : KinematicBody2D
  4. {
  5. [Export] public int speed = 200;
  6. public Vector2 velocity = new Vector2();
  7. public void GetInput()
  8. {
  9. velocity = new Vector2();
  10. if (Input.IsActionPressed("right"))
  11. velocity.x += 1;
  12. if (Input.IsActionPressed("left"))
  13. velocity.x -= 1;
  14. if (Input.IsActionPressed("down"))
  15. velocity.y += 1;
  16. if (Input.IsActionPressed("up"))
  17. velocity.y -= 1;
  18. velocity = velocity.Normalized() * speed;
  19. }
  20. public override void _PhysicsProcess(float delta)
  21. {
  22. GetInput();
  23. velocity = MoveAndSlide(velocity);
  24. }
  25. }

In the get_input() function, we check for the four key events and sum them up to get the velocity vector. This has the benefit of making two opposite keys cancel each other out, but will also result in diagonal movement being faster due to the two directions being added together.

如果我们让速度 归一化 , 我们可以防止这种情况 ,这意味着我们将其 长度 设置为 1 ,并乘以所期望速度。

小技巧

如果你之前从未接触过向量数学,或者需要复习,你可以在 向量数学 看到Godot中向量用法的解释。

注解

If the code above does nothing when you press the keys, double-check that you’ve set up input actions correctly as described in the 场景布置 part of this tutorial.

旋转+移动

这种类型的运动有时被称为“Asteroids式运动”,因为它类似于经典街机游戏Asteroids的工作方式。 按左/右旋转角色,而按上/下使得角色在面向的方向上向前或向后。

../../_images/movement_rotate1.gif

GDScript

C#

  1. extends KinematicBody2D
  2. export (int) var speed = 200
  3. export (float) var rotation_speed = 1.5
  4. var velocity = Vector2()
  5. var rotation_dir = 0
  6. func get_input():
  7. rotation_dir = 0
  8. velocity = Vector2()
  9. if Input.is_action_pressed('right'):
  10. rotation_dir += 1
  11. if Input.is_action_pressed('left'):
  12. rotation_dir -= 1
  13. if Input.is_action_pressed('down'):
  14. velocity = Vector2(-speed, 0).rotated(rotation)
  15. if Input.is_action_pressed('up'):
  16. velocity = Vector2(speed, 0).rotated(rotation)
  17. func _physics_process(delta):
  18. get_input()
  19. rotation += rotation_dir * rotation_speed * delta
  20. velocity = move_and_slide(velocity)
  1. using Godot;
  2. using System;
  3. public class Movement : KinematicBody2D
  4. {
  5. [Export] public int speed = 200;
  6. [Export] public float rotationSpeed = 1.5f;
  7. public Vector2 velocity = new Vector2();
  8. public int rotationDir = 0;
  9. public void GetInput()
  10. {
  11. rotationDir = 0;
  12. velocity = new Vector2();
  13. if (Input.IsActionPressed("right"))
  14. rotationDir += 1;
  15. if (Input.IsActionPressed("left"))
  16. rotationDir -= 1;
  17. if (Input.IsActionPressed("down"))
  18. velocity = new Vector2(-speed, 0).Rotated(Rotation);
  19. if (Input.IsActionPressed("up"))
  20. velocity = new Vector2(speed, 0).Rotated(Rotation);
  21. velocity = velocity.Normalized() * speed;
  22. }
  23. public override void _PhysicsProcess(float delta)
  24. {
  25. GetInput();
  26. Rotation += rotationDir * rotationSpeed * delta;
  27. velocity = MoveAndSlide(velocity);
  28. }
  29. }

我们添加了两个新变量来跟踪旋转方向和速度。同样,一次按下两个键将相互抵消并导致没有旋转。旋转直接应用于物体的 rotation 属性上。

为了设定速度,我们使用 Vector2.rotated() 方法,使它的指向与物体方向相同。 rotated() 是一个很有用的向量函数,你可以在许多情况下使用它,否则就需要用到三角函数。

旋转+移动(鼠标)

这种运动方式是前一种运动方式的变体。 这次,方向由鼠标位置而不是键盘设置。 角色将始终“看向”鼠标指针。 前进/后退输入保持不变。

../../_images/movement_rotate2.gif

GDScript

C#

  1. extends KinematicBody2D
  2. export (int) var speed = 200
  3. var velocity = Vector2()
  4. func get_input():
  5. look_at(get_global_mouse_position())
  6. velocity = Vector2()
  7. if Input.is_action_pressed('down'):
  8. velocity = Vector2(-speed, 0).rotated(rotation)
  9. if Input.is_action_pressed('up'):
  10. velocity = Vector2(speed, 0).rotated(rotation)
  11. func _physics_process(delta):
  12. get_input()
  13. velocity = move_and_slide(velocity)
  1. using Godot;
  2. using System;
  3. public class Movement : KinematicBody2D
  4. {
  5. [Export] public int speed = 200;
  6. public Vector2 velocity = new Vector2();
  7. public void GetInput()
  8. {
  9. LookAt(GetGlobalMousePosition());
  10. velocity = new Vector2();
  11. if (Input.IsActionPressed("down"))
  12. velocity = new Vector2(-speed, 0).Rotated(Rotation);
  13. if (Input.IsActionPressed("up"))
  14. velocity = new Vector2(speed, 0).Rotated(Rotation);
  15. velocity = velocity.Normalized() * speed;
  16. }
  17. public override void _PhysicsProcess(float delta)
  18. {
  19. GetInput();
  20. velocity = MoveAndSlide(velocity);
  21. }
  22. }

这里我们用到 Node2D 中的 look_at() 方法,使游戏角色朝向给定的位置。 如果没有此函数,为获得相同的效果,可能需要像下面这样设置角度:

GDScript

C#

  1. rotation = get_global_mouse_position().angle_to_point(position)
  1. var rotation = GetGlobalMousePosition().AngleToPoint(Position);

点击并移动

最后一个示例仅使用鼠标来控制角色。 单击屏幕将使游戏角色移动到目标位置。

../../_images/movement_click.gif

GDScript

C#

  1. extends KinematicBody2D
  2. export (int) var speed = 200
  3. var target = Vector2()
  4. var velocity = Vector2()
  5. func _input(event):
  6. if event.is_action_pressed('click'):
  7. target = get_global_mouse_position()
  8. func _physics_process(delta):
  9. velocity = position.direction_to(target) * speed
  10. # look_at(target)
  11. if position.distance_to(target) > 5:
  12. velocity = move_and_slide(velocity)
  1. using Godot;
  2. using System;
  3. public class Movement : KinematicBody2D
  4. {
  5. [Export] public int speed = 200;
  6. public Vector2 target = new Vector2();
  7. public Vector2 velocity = new Vector2();
  8. public override void _Input(InputEvent @event)
  9. {
  10. if (@event.IsActionPressed("click"))
  11. {
  12. target = GetGlobalMousePosition();
  13. }
  14. }
  15. public override void _PhysicsProcess(float delta)
  16. {
  17. velocity = Position.DirectionTo(target) * speed;
  18. // LookAt(target);
  19. if (Position.DistanceTo(target) > 5)
  20. {
  21. velocity = MoveAndSlide(velocity);
  22. }
  23. }
  24. }

注意我们在移动之前做的 distance_to() 检查。 如果没有这个检查,物体在到达目标位置时会“抖动”,因为它稍微移过该位置时就会试图向后移动,只是每次移动步长都会有点远从而导致来回重复移动。

如果你喜欢, 取消注释的 rotation 代码可以使物体转向其运动方向。

小技巧

该技术也可以用到“跟随”的游戏角色中。 目标 位置可以是任何你想移动到的对象的位置。

总结

你可能觉得这些代码示例可以作为你自己的项目的一个有用的出发点。 请随意使用它们并试验它们,看看你能做些什么。

可以在此处下载此示例项目: 2D_movement_demo.zip