Godot 4.x.
Hello Godot forums!
I just began learning GDScript - and I am working on a scene where I want the player to be able to drag a node “A” around within the boundaries of an Area2D (defined by a collisionShape2D “restrictionZone”).
I want A to keep following the mouse cursor even if it’s outside, without being able to leave restrictionZone (basically follow along the boundaries).
func _on_area_2d_mouse_entered() -> void:
mouse_in = true
func _on_area_2d_mouse_exited() -> void:
mouse_in = false
func move_target(delta: float) -> void:
var mouse_position = get_global_mouse_position()
if is_following:
target = mouse_position
else:
target = original_position
if is_following and !mouse_in
#restrictionZone is a CollisionShape2D
target = restrictionZone.get_closest_point(target)
A.position = A.position.move_toward(target, speed * delta)
The code above is not working, because get_closest point is not the right method, but it’s the the closest one I know.
The reason why I don’t want to use math for it is because I intend to re-use this with different shapes and sizes, and keep it future proof for best practice.
Thanks in advance for your help!