鼠标和输入坐标
关于
这个小教程的目的是为了清除许多关于输入坐标、获取鼠标位置和屏幕分辨率等常见错误。
硬件显示坐标
Using hardware coordinates makes sense in the case of writing complex UIs meant to run on PC, such as editors, MMOs, tools, etc. However, it does not make as much sense outside of that scope.
视区显示坐标
Godot使用视区显示内容,并且视区可以通过几个选项进行缩放(参见 多分辨率 教程)。然后,使用节点中的函数来获得鼠标坐标和视区大小,例如:
GDScript
C#
func _input(event):
# Mouse in viewport coordinates.
if event is InputEventMouseButton:
print("Mouse Click/Unclick at: ", event.position)
elif event is InputEventMouseMotion:
print("Mouse Motion at: ", event.position)
# Print the size of the viewport.
print("Viewport Resolution is: ", get_viewport_rect().size)
public override void _Input(InputEvent @event)
{
// Mouse in viewport coordinates.
if (@event is InputEventMouseButton eventMouseButton)
GD.Print("Mouse Click/Unclick at: ", eventMouseButton.Position);
else if (@event is InputEventMouseMotion eventMouseMotion)
GD.Print("Mouse Motion at: ", eventMouseMotion.Position);
// Print the size of the viewport.
GD.Print("Viewport Resolution is: ", GetViewportRect().Size);
}
Alternatively, it’s possible to ask the viewport for the mouse position:
GDScript
C#
get_viewport().get_mouse_position()
GetViewport().GetMousePosition();
注解
When the mouse mode is set to Input.MOUSE_MODE_CAPTURED
, the event.position
value from InputEventMouseMotion
is the center of the screen. Use event.relative
instead of event.position
and event.speed
to process mouse movement and position changes.