#Best 2D Drag and Drop system with physics

1 messages · Page 1 of 1 (latest)

hardy jasper
#

hello everyone. So I have been trying to research a drag and drop system for a mobile game that teaches kids language. The idea is when kids drag object, it plays audio in the desired lanuage. I have been looking at other sophisticated games that have great dran drop systems like toca boca and avatar world. I started with an area 2D but that didnt help when object needed to be dropped and fall to the ground. I then tried rigid node and eventually I am using character2D node as it can use scripted velocity with physics. my issue is the test bject begins by dropping and landing on the floor but I can't seem to be able to pick it up again. Will put code in comments

#

extends CharacterBody2D
class_name Draggable # Makes this script a globally accessible class

-----------------

Object Properties

-----------------

Use an enum to classify objects for specific drop zones.

enum ObjectType { BED, TABLE, CHAIR, ALL }

@export var object_type: ObjectType = ObjectType.BED
@export var gravity: float = 1200.0
@export var snap_offset: float = 0.0 # Vertical offset for snapping to a drop zone
@export var pickup_sound: AudioStream
@export var drop_sound: AudioStream
@export var texture: Texture2D # Texture for the object's sprite
@export var start_scale: Vector2 = Vector2(1, 1)

-----------------

Internal State

-----------------

var is_dragging: bool = false
var target_zone: Area2D = null

hardy jasper
#

Node References

@onready var sprite: Sprite2D = $Sprite
@onready var audio_player: AudioStreamPlayer = $AudioStreamPlayer
@onready var collider: CollisionShape2D = $Collider


Initialization

func _ready() -> void:
if texture:
sprite.texture = texture
sprite.scale = start_scale


Drag & Drop Logic

func start_drag() -> void:
is_dragging = true
z_index = 100
set_physics_process(false)

if pickup_sound:
    audio_player.stream = pickup_sound
    audio_player.play()

func end_drag() -> void:
is_dragging = false
z_index = 0
set_physics_process(true)

if drop_sound:
    audio_player.stream = drop_sound
    audio_player.play()

if target_zone:
    global_position = Vector2(global_position.x, target_zone.global_position.y - snap_offset)
    velocity.y = 0.0
else:
    velocity = Vector2.ZERO
#

Drop Zone Interaction

func set_target_zone(zone: Area2D) -> void:
target_zone = zone