Alright, let's say our NPC-scene looks like this:
- NPC (type: Area2D)
- Sprite (type: Sprite)
- Hitbox (type: CollisionShape2D)
Next, attach a script to the root-node (the one we called "NPC"):
extends Area2D
signal open_menu
signal exit_menu
var stats = {
"health": 10,
"max_health": 100,
"occupation": "Game Developer"
}
func _on_NPC_input_event(viewport, event, shape_idx):
if event is InputEventMouseButton and event.pressed:
if event.button_index == BUTTON_LEFT:
emit_signal("open_menu", stats)
elif event.button_index == BUTTON_RIGHT:
emit_signal("exit_menu")
We have three stats here ("health", "max_health" and "occupation") grouped together in a dictionary called stats
. The function has to be connected to the input_event
-signal of the Area2D-node, it's the first entry under "CollisionObject2D".
Now create another scene that looks like this:
- Root (type: Node2D, doesn't matter much)
- NPC (inherited from the scene we just created)
- Menu (type: Label, for simplicity reasons)
Add a script to the root-node here as well:
extends Node2D
func _on_NPC_open_menu(stats):
$Menu.text = "%s / %s, %s" % [stats["health"], stats["max_health"], stats["occupation"]]
$Menu.show()
func _on_NPC_exit_menu():
$Menu.text = ""
$Menu.hide()
Make sure you connect the open_menu
- and exit_menu
-signals of the inherited NPC scene to the functions in this script. If you now run the scene and click inside the area of the NPC's hitbox, it will emit the open_menu
-signal along with it's stats. Which are then grabbed by the "Root"-node, converted into a string (using format strings) and assigned to our label called "Menu". Clicking with the right mouse button will emit exit_menu
, thus reset the labels text and hide it again.