输入示例

前言

在本教程中, 你将学习如何使用Godot的 输入事件 系统捕获玩家输入. 你的游戏可以使用多种不同类型的输入——键盘, 游戏手柄, 鼠标等等. 还有许多不同的方法, 将这些输入转化为游戏中的动作. 本文将向你展示一些最常见的场景, 你可以将其作为你自己项目的起点.

备注

要详细了解 Godot 的输入事件系统是如何工作的,请参阅 使用 InputEvent

事件和轮询

有时你想让你的游戏对某一输入事件作出反应—例如按下 “跳跃” 按钮. 在其他情况下, 你可能希望只要有一个键被按下就会发生一些事情, 比如移动. 在第一种情况下, 你可以使用 _input() 函数, 只要有输入事件发生就会调用该函数. 在第二种情况下,Godot提供了 Input 单例, 你可以用它来查询一个输入的状态.

示例:

GDScriptC#

  1. func _input(event):
  2. if event.is_action_pressed("jump"):
  3. jump()
  4. func _physics_process(delta):
  5. if Input.is_action_pressed("move_right"):
  6. # Move as long as the key/button is pressed.
  7. position.x += speed * delta
  1. public override void _Input(InputEvent @event)
  2. {
  3. if (@event.IsActionPressed("jump"))
  4. {
  5. Jump();
  6. }
  7. }
  8. public override void _PhysicsProcess(double delta)
  9. {
  10. if (Input.IsActionPressed("move_right"))
  11. {
  12. // Move as long as the key/button is pressed.
  13. position.X += speed * (float)delta;
  14. }
  15. }

这使你能够灵活地混合和匹配所执行输入的处理类型.

对于本教程的其余部分, 我们将专注于使用 _input () 捕捉单个事件.

输入事件

输入事件是继承自 输入事件 的对象. 根据事件类型, 对象将包含与该事件相关的特定属性. 为了了解事件的实际情况, 添加一个节点并附加以下脚本:

GDScriptC#

  1. extends Node
  2. func _input(event):
  3. print(event.as_text())
  1. using Godot;
  2. public partial class Node : Godot.Node
  3. {
  4. public override void _Input(InputEvent @event)
  5. {
  6. GD.Print(@event.AsText());
  7. }
  8. }

当你按下按键, 移动鼠标, 并执行其他输入, 你会在输出窗口中看到每个事件滚动. 下面是输出的一个例子:

  1. A
  2. Mouse motion at position ((971, 5)) with velocity ((0, 0))
  3. Right Mouse Button
  4. Mouse motion at position ((870, 243)) with velocity ((0.454937, -0.454937))
  5. Left Mouse Button
  6. Mouse Wheel Up
  7. A
  8. B
  9. Shift
  10. Alt+Shift
  11. Alt
  12. Shift+T
  13. Mouse motion at position ((868, 242)) with velocity ((-2.134768, 2.134768))

如你所见, 对于不同类型的输入, 结果是非常不同的. 按键事件甚至被打印为按键符号. 例如, 让我们考虑 鼠标按钮输入事件 . 它继承自以下类:

小技巧

在处理事件时, 打开类引用是一个好主意, 这样可以检查事件类型的可用属性和方法.

如果你尝试访问不包含属性的输入类型上的属性, 则可能会遇到错误-例如, 对 InputEventKey 调用 Position . 要避免这种情况, 请确保首先测试事件类型:

GDScriptC#

  1. func _input(event):
  2. if event is InputEventMouseButton:
  3. print("mouse button event at ", event.position)
  1. public override void _Input(InputEvent @event)
  2. {
  3. if (@event is InputEventMouseButton mouseEvent)
  4. {
  5. GD.Print("mouse button event at ", mouseEvent.Position);
  6. }
  7. }

InputMap

The InputMap is the most flexible way to handle a variety of inputs. You use this by creating named input actions, to which you can assign any number of input events, such as keypresses or mouse clicks. To see them, and to add your own, open Project -> Project Settings and select the InputMap tab:

../../_images/inputs_inputmap.webp

小技巧

A new Godot project includes a number of default actions already defined. To see them, turn on Show Built-in Actions in the InputMap dialog.

捕捉动作

一旦你定义了动作, 可以在脚本中使用 is_action_pressed()is_action_released () 处理它们. 通过名称查找响应的动作:

GDScriptC#

  1. func _input(event):
  2. if event.is_action_pressed("my_action"):
  3. print("my_action occurred!")
  1. public override void _Input(InputEvent @event)
  2. {
  3. if (@event.IsActionPressed("my_action"))
  4. {
  5. GD.Print("my_action occurred!");
  6. }
  7. }

键盘事件

键盘事件在 InputEventKey 中被捕获. 虽然建议使用输入动作来代替, 但在某些情况下, 你可能会想专门查看按键事件. 对于当前示例, 来检查一下 T :

GDScriptC#

  1. func _input(event):
  2. if event is InputEventKey and event.pressed:
  3. if event.keycode == KEY_T:
  4. print("T was pressed")
  1. public override void _Input(InputEvent @event)
  2. {
  3. if (@event is InputEventKey keyEvent && keyEvent.Pressed)
  4. {
  5. if (keyEvent.Keycode == Key.T)
  6. {
  7. GD.Print("T was pressed");
  8. }
  9. }
  10. }

小技巧

See @GlobalScope_Key for a list of keycode constants.

警告

由于键盘冲突,如果你一次性按下了太多的键,那么在特定时间点,可能是无法将所有按键输入都进行注册的。根据按键在键盘上位置的不同,某些按键产生冲突的可能性会比其他的要高。有些键盘在硬件层面会提供抗冲突功能,不过在低端键盘和笔记本键盘上很少见。

因此,建议使用能够在不具备抗冲突功能的键盘上也能正常工作的默认键盘布局。详情请参阅这个 Gamedev Stack Exchange 问题

键盘修饰键

修饰键属性继承自 InputEventWithModifiers ,可使用布尔属性检查修饰键的组合。试想,如果需要在按下 T 时发生一件事,而按下 Shift + T 时发生不同的事:

GDScriptC#

  1. func _input(event):
  2. if event is InputEventKey and event.pressed:
  3. if event.keycode == KEY_T:
  4. if event.shift_pressed:
  5. print("Shift+T was pressed")
  6. else:
  7. print("T was pressed")
  1. public override void _Input(InputEvent @event)
  2. {
  3. if (@event is InputEventKey keyEvent && keyEvent.Pressed)
  4. {
  5. switch (keyEvent.Keycode)
  6. {
  7. case Key.T:
  8. GD.Print(keyEvent.ShiftPressed ? "Shift+T was pressed" : "T was pressed");
  9. break;
  10. }
  11. }
  12. }

小技巧

See @GlobalScope_Key for a list of keycode constants.

鼠标事件

鼠标事件继承自 InputEventMouse 并被分成 InputEventMouseButtonInputEventMouseMotion 两种类型。注意,这意味着所有鼠标事件都包含 position 属性。

鼠标按钮

Capturing mouse buttons is very similar to handling key events. @GlobalScope_MouseButton contains a list of MOUSE_BUTTON_* constants for each possible button, which will be reported in the event’s button_index property. Note that the scrollwheel also counts as a button - two buttons, to be precise, with both MOUSE_BUTTON_WHEEL_UP and MOUSE_BUTTON_WHEEL_DOWN being separate events.

GDScriptC#

  1. func _input(event):
  2. if event is InputEventMouseButton:
  3. if event.button_index == MOUSE_BUTTON_LEFT and event.pressed:
  4. print("Left button was clicked at ", event.position)
  5. if event.button_index == MOUSE_BUTTON_WHEEL_UP and event.pressed:
  6. print("Wheel up")
  1. public override void _Input(InputEvent @event)
  2. {
  3. if (@event is InputEventMouseButton mouseEvent && mouseEvent.Pressed)
  4. {
  5. switch (mouseEvent.ButtonIndex)
  6. {
  7. case MouseButton.Left:
  8. GD.Print($"Left button was clicked at {mouseEvent.Position}");
  9. break;
  10. case MouseButton.WheelUp:
  11. GD.Print("Wheel up");
  12. break;
  13. }
  14. }
  15. }

鼠标行为

InputEventMouseMotion 只要鼠标移动就会发生事件. 可以通过 relative 属性找到移动的距离.

Here’s an example using mouse events to drag-and-drop a Sprite2D node:

GDScriptC#

  1. extends Node
  2. var dragging = false
  3. var click_radius = 32 # Size of the sprite.
  4. func _input(event):
  5. if event is InputEventMouseButton and event.button_index == MOUSE_BUTTON_LEFT:
  6. if (event.position - $Sprite2D.position).length() < click_radius:
  7. # Start dragging if the click is on the sprite.
  8. if not dragging and event.pressed:
  9. dragging = true
  10. # Stop dragging if the button is released.
  11. if dragging and not event.pressed:
  12. dragging = false
  13. if event is InputEventMouseMotion and dragging:
  14. # While dragging, move the sprite with the mouse.
  15. $Sprite2D.position = event.position
  1. using Godot;
  2. public partial class MyNode2D : Node2D
  3. {
  4. private bool _dragging = false;
  5. private int _clickRadius = 32; // Size of the sprite.
  6. public override void _Input(InputEvent @event)
  7. {
  8. Sprite2D sprite = GetNodeOrNull<Sprite2D>("Sprite2D");
  9. if (sprite == null)
  10. {
  11. return; // No suitable node was found.
  12. }
  13. if (@event is InputEventMouseButton mouseEvent && mouseEvent.ButtonIndex == MouseButton.Left)
  14. {
  15. if ((mouseEvent.Position - sprite.Position).Length() < _clickRadius)
  16. {
  17. // Start dragging if the click is on the sprite.
  18. if (!_dragging && mouseEvent.Pressed)
  19. {
  20. _dragging = true;
  21. }
  22. }
  23. // Stop dragging if the button is released.
  24. if (_dragging && !mouseEvent.Pressed)
  25. {
  26. _dragging = false;
  27. }
  28. }
  29. else
  30. {
  31. if (@event is InputEventMouseMotion motionEvent && _dragging)
  32. {
  33. // While dragging, move the sprite with the mouse.
  34. sprite.Position = motionEvent.Position;
  35. }
  36. }
  37. }
  38. }

触摸事件

如果你使用的是触摸屏设备,就可以生成触摸事件。InputEventScreenTouch 相当于鼠标点击事件,而 InputEventScreenDrag 的工作原理与鼠标移动一致。

小技巧

要在非触摸屏设备上测试触摸事件,请打开“项目设置”,进入“Input Devices/Pointing”(输入设备/触点)部分。启用“Emulate Touch From Mouse”(根据鼠标模拟触摸),你的项目将把鼠标单击和移动解释为触摸事件。

Previous Next


© 版权所有 2014-present Juan Linietsky, Ariel Manzur and the Godot community (CC BY 3.0). Revision b1c660f7.

Built with Sphinx using a theme provided by Read the Docs.