Up to date

This page is up to date for Godot 4.2. If you still find outdated information, please open an issue.

滑鼠和輸入座標

關於

這個小教學旨在理清許多關於輸入座標、獲取滑鼠位置和螢幕解析度等的常見錯誤。

硬體顯示座標

使用硬體座標在編寫要在 PC 上運作的複雜 UI 時是有意義的,比如編輯器、網路遊戲、工具等。然而,在這個範圍之外,它就沒有那麼大的意義了。

視口顯示座標

Godot 使用視口(Viewport)顯示內容,並且視口可以通過若干選項進行縮放(參見 多解析度 教學)。然後,使用節點中的函式來獲得滑鼠座標和視口大小,例如:

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().get_visible_rect().size)

另外,也可以從視口查詢滑鼠的座標:

get_viewport().get_mouse_position()

備註

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.velocity to process mouse movement and position changes.