TinyAdventure/objects/pickup_item.gd

60 lines
1.5 KiB
GDScript

@tool
class_name PickupItem
extends Node3D
signal item_picked_up(node_path:NodePath)
@onready var world_item_node = %WorldItemNode
@export var item:ItemResource:
get:
return item
set(value):
if value != item:
item = value
if world_item_node == null:
return
for child in world_item_node.get_children():
child.get_parent().remove_child(child)
child.queue_free()
world_item_node.add_child(item.scene.instantiate())
var gravity = ProjectSettings.get_setting("physics/3d/default_gravity")
var world_item_initial_y_position: float = 0
var world_item_initial_y_velocity: float = 0
var world_item_y_velocity: float = 0.
func _ready():
if item == null:
push_error ("Error: invalid PickupItem at %s" % str(global_position))
return
var item_scene = item.scene.instantiate()
world_item_node.add_child(item_scene)
world_item_node.position.y = world_item_initial_y_position
world_item_y_velocity = world_item_initial_y_velocity
func _on_area_3d_body_entered(body):
if body.has_method("on_item_picked_up"):
body.on_item_picked_up(item)
item_picked_up.emit(get_path())
queue_free()
func _physics_process(delta: float) -> void:
if world_item_node.position.y > 0:
world_item_y_velocity -= gravity * delta
world_item_node.position.y += world_item_y_velocity * delta
if world_item_node.position.y < 0:
world_item_node.position.y = 0
if world_item_y_velocity < -1:
world_item_node.position.y = 0.01
world_item_y_velocity *= -0.4
else:
world_item_y_velocity = 0