Thank you!
What I am doing at the moment though, is not worry too much about types and for this specific case it’s not perfectly types but I do checks where needed.
So the system I build now is this: There are two “magic” functions. The first one is:
func get_view_label_text() -> String:
When a script has this, whatever string it returns is shown under the crosshair.
For example, on my door script I have:
func get_view_label_text() -> String:
if state == DoorState.OPEN:
return "Close door"
else:
return "Open door"
And then you get something like this in game:
Similarly, I have a function for interactions:
func on_interaction(player: Player) -> void:
This is called whenever a user clicks while looking at an object with a script that has this.
In my player script I check if these functions exist, and then call them if they do exist. And I check parents of objects too so I can have multiple colliders/areas on a single object with a script on the parent.
For that, the implementation is:
func _process(_delta: float) -> void:
# Allow us to quit
if Input.is_action_just_pressed("quit_game"):
get_tree().quit()
update_view_label()
handle_interacting()
func update_view_label() -> void:
# Update the crosshair/view label depending on what we're looking at
var view_label_text: String = ""
if interaction_ray.is_colliding():
var collider: Node = interaction_ray.get_collider()
view_label_text = call_on_node_or_parent(collider, GET_VIEW_LABEL_TEXT_FUNC_NAME, [], "")
if view_label_text:
view_label.visible = true
view_label.text = view_label_text
else:
view_label.visible = false
func handle_interacting() -> void:
var collider: Node = interaction_ray.get_collider()
if collider && Input.is_action_just_pressed("primary_action"):
call_on_node_or_parent(collider, ON_INTERACTION_FUNC_NAME, [self])
func call_on_node_or_parent(
node: Node, function_name: String, arg_array: Array, default: Variant = null
) -> Variant:
while node:
if node.has_method(function_name):
return node.callv(function_name, arg_array)
node = node.get_parent()
return default
So this part isn’t perfectly typed, I add types where needed but there is some untyped stuff (well, “typed” with Variant
and Array
).
This seems to work well so far. I have an apple I can pick up (doesn’t go into an inventory yet as I don’t have that, but the interaction works) and a door I can open/close. Adding these methods to the scripts has been very simple and very nice to use.
I hope this might help anybody trying to do something similar! Or if you have comments on how I can improve this or problems you see, I’d love to hear about that too!