How do I make this button only show when 2 characters are close enough?

Godot Version

4.2

Question

I have a button that I would like to have show up only when two playable characters are close enough to each other (1 unit apart), and either one of them or both of them are carrying at least one item, but whenever I move one character 1 unit away from another, then cancel my move, and move that character to a position that is more than 1 unit away from the other, the button still shows up. Here is what I currently have typed out. It’s in the _process function:

> for p in get_tree().get_nodes_in_group("Players"):
> 	if abs(p.global_position.x - destination_cell["location"].x) + abs(p.global_position.z - destination_cell["location"].z) == 1:
> 		if selected_char.inventory_count > 0 or p.inventory_count > 0:
> 			battle_menu.trade_button.show()
> 		else:
> 			battle_menu.trade_button.hide()

Try using distance_squared_to and combining all of your if statements. Maybe add a break if one is found.

for p in get_tree().get_nodes_in_group("Players"):
    var nearby: bool = p.global_position.distance_squared_to(destination_cell["location"]) == 1
    var can_trade: bool = selected_char.inventory_count > 0 or p.inventory_count > 0

    battle_menu.trade_button.visible = nearby and can_trade
    if battle_menu.trade_button.visible:
        break

I think your error comes from the outer if statement for distance check, rather than it being flat. Also continuing to iterate even after finding a valid trade will cause issues when there are more than two players.

1 Like

That works! Thank you!

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.