xiandie/scene/little_game/gadget/wheel.gd

48 lines
1.5 KiB
GDScript3
Raw Normal View History

extends Control
# A wheel that can be rotated by the player.
# Detects the angle of the wheel and emits a signal when the wheel is rotated.
# The value might be positive or negative, and the negative value means the wheel is rotated in clockwise.
signal rotated(radiant: float)
@export var enabled := true:
set(val):
enabled = val
dragging = false
@export var min_angle := 30.0
@export var one_direction := true
@export var clockwise := true
var start_pos := Vector2.ZERO
var dragging := false
func _input(event: InputEvent) -> void:
if not enabled:
return
if event is InputEventMouseButton:
if event.button_index == MOUSE_BUTTON_LEFT:
if event.pressed:
start_pos = event.position
dragging = true
else:
dragging = false
# print("mouse button")
elif event is InputEventMouseMotion:
if dragging:
var current_pos = event.position
# current node's viewport position
var origin := get_viewport().global_canvas_transform * global_position
# Calculate the angle between the start_pos and the current_pos around the origin.
var radiant = (current_pos - origin).angle_to(start_pos - origin)
var min_rad = min_angle * PI / 180
if abs(radiant) > min_rad:
# check if the wheel is rotated in the correct direction
if one_direction:
if (clockwise and radiant > 0) or (not clockwise and radiant < 0):
start_pos = current_pos
return
rotated.emit(radiant)
start_pos = current_pos
# print(radiant, current_pos)