Godot Version
v4.7.stable
Question
I had been following a drag and drop inventory tutorial by Octodemy. Since I completed it, I’ve been trying to convert it to 2D, but I’ve had some difficulty with the picking up mechanics since it requires the project_ray_normal and project_ray_origin function. This leads to my query, is there an alternative to project_ray_ for 2D or at least a way to do it in 2D?
Current code for drop_area.gd:
extends Control
const ITEM_2D = preload("res://item_2d.tscn")
func _can_drop_data(_at_position: Vector2, _data: Variant) -> bool:
return true
func _drop_data(_at_position: Vector2, data: Variant) -> void:
var node = ITEM_2D.instantiate()
node.set_meta("item_data", data.item)
node.get_node("MeshInstance2D").mesh = data.item.mesh
get_tree().current_scene.add_child(node)
data.item = null
node.global_position = Vector2(0, 254)
func _notification(what: int) -> void:
if what == Node.NOTIFICATION_DRAG_BEGIN:
mouse_filter = Control.MOUSE_FILTER_PASS
if what == Node.NOTIFICATION_DRAG_END:
mouse_filter = Control.MOUSE_FILTER_IGNORE
func _unhandled_input(event: InputEvent) -> void:
if event is InputEventMouseButton:
if event.pressed:
print("Pressed")
var cam := get_viewport().get_camera_2d()
var space := cam.get_world_2d().direct_space_state
var param = PhysicsRayQueryParameters2D.new()
param.from = cam.project_ray_origin(event.position)
param.to = param.from + cam.project_ray_normal(event.position) * 100
var ray := space.intersect_ray(param)
if ray and ray["collider"] is RigidBody2D:
var world_item = ray["collider"]
for slot in %GridContainer.get_children():
if slot.item: continue
#Goes to first empty slot
slot.item = ray["collider"].get_meta("item_data")
slot.update_ui()
world_item.queue_free()
break