Skip to content

Instantly share code, notes, and snippets.

@NickHatBoecker
Created January 5, 2024 18:38
Show Gist options
  • Save NickHatBoecker/c3025a1a158047f5f91798ec0c6891f7 to your computer and use it in GitHub Desktop.
Save NickHatBoecker/c3025a1a158047f5f91798ec0c6891f7 to your computer and use it in GitHub Desktop.
A drag 'n drop Godot 3 example

This is a drag 'n drop Godot 3 example.

Example

You found 4 pieces of paper and now you have to arrange them in order to read the message on it.

Instructions

  1. Add a scene with a Node2D element.
  2. Connect ShapeMinigame.gd script to it.
  3. Add multiple KinematicBody2D elements with a Rectangular CollisionShape2D and, if you want, a Sprite.
  4. Connect DragElement.gd script to it.
  5. Set targetPosition per KinematicBody2D element.
  6. Create a SuccessLabel, which will be shown as soon as all elements have reached target position.
  7. Have fun!
extends KinematicBody2D
signal has_reached_target_position
export var targetPosition = Vector2(-1, -1)
var isDragging: bool = false
var hasReachedTargetPosition: bool = false
func _ready() -> void:
add_to_group("Draggables")
input_pickable = true
func _process(_delta) -> void:
if hasReachedTargetPosition: return
if isDragging:
z_index = 2 # So draggable element is always on top
position = get_viewport().get_mouse_position()
else:
z_index = 0
func _on_input_event(_viewport, event, _shape_idx) -> void:
if hasReachedTargetPosition: return
if event is InputEventMouseButton:
if event.button_index == BUTTON_LEFT and event.pressed:
isDragging = true
elif event.button_index == BUTTON_LEFT and not event.pressed:
_on_drag_end()
elif event is InputEventScreenTouch:
if event.pressed and event.get_index() == 0:
position = event.get_position()
func _on_drag_end() -> void:
isDragging = false
# Check if target position was reached
if position.ceil() == targetPosition:
_on_target_position_reached()
func _on_target_position_reached() -> void:
hasReachedTargetPosition = true
emit_signal('has_reached_target_position')
z_index = 0
extends Node2D
var dragElements = []
var numDragElementsHaveReachedTargetPosition = 0
func _ready() -> void:
dragElements = get_tree().get_nodes_in_group("Draggables")
for node in dragElements:
node.connect("has_reached_target_position", self, "_on_element_has_reached_target_position")
func _on_element_has_reached_target_position() -> void:
numDragElementsHaveReachedTargetPosition += 1
if numDragElementsHaveReachedTargetPosition == dragElements.size():
$SuccessLabel.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment