Michael Teasdale
Michael Teasdale

Reputation: 113

How do I pick up a light in Godot 4?

I've got a character in a 2d game capable of picking up and dropping objects to/from an inventory panel. One thing I can pick up is a lamp (PointLight2D). When I have a lamp in certain inventory slots, I want the character to light up as well (they're carrying the lamp. Complications: The player can turn the light off and on. A light that is on will burn out over time whether it's in inventory or on the ground (there's a timer node under to the PointLight2D). When the player drops the lamp, the character should stop shining. The player and lamp are part of the main game world. The inventory is part of a HUD on a separate overlapping viewport.

I tried adding a PointLight2D with timer to my character, but then I have the problem of synchronizing the light in inventory to the light owned by the character. I tried duplicating the light and timer using duplicate(), but the character doesn't shine when I do that. Anyone have any suggestions? I'm sure this problem is solved somewhere, but I haven't been able to find it, and haven't been able to think my way through to a solution.

Light item node tree. Player character node tree.

Upvotes: 0

Views: 177

Answers (1)

Michael Teasdale
Michael Teasdale

Reputation: 113

After a few days of trying different things, I decided on this: When a light is picked up, detach the source from the item. Add the source as a child of the character.

When a light is dropped, detach the source from the character and re-add it as a child of the light.

Picking up and dropping are triggered by signals, so in the character the code looks like this:

func _on_pickup(item: Item) -> void:
    if item is Light:
        var light = item.get_node("Source")
        item.remove_child(light)
        add_child(light)


func _on_drop(item: Item) -> void:
    if item is Light and !item.has_node("Source"):
        var light = get_node("Source")
        remove_child(light)
        item.add_child(light)

Upvotes: 0

Related Questions