How do I make when 2 bodies entered the door the function will happen?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By si444n

I have a problem when one of the player entered the door the game will end and I want when one of the player entered the door the wont end and it will need the 2 players to be on the door to end. So here my code and i tried using ‘and’/‘&&’ and still wont work.

extends Area2D



func _on_GoalDoor_body_entered(body):
	if body.name == "Player":
		body.end()
	if body.name == "Player2":
		body.end()
:bust_in_silhouette: Reply From: zeludtnecniv

You need to save wich body enter and exit your Area2D. Use this with the signal “body_entered” and the signal “body_exited”.

extends Area2D

var player1 = null
var player2 = null

func _on_GoalDoor_body_exited(body):
	if body.name == "Player":
		player1 = null
	if body.name == "Player2":
		player2 = null


func _on_GoalDoor_body_entered(body):
	if body.name == "Player":
		player1 = body
	if body.name == "Player2":
		player2 = body
	if (player1 != null and player2 != null):
		player1.end();
		player2.end();

Depending on the details, you might be able to get away with something a bit simpler by just counting the entries and exits… Untested, but something like:

extends Area2D

var players_in_door = 0

func _on_GoalDoor_body_exited(body):
    players_in_door -= 1

func _on_GoalDoor_body_entered(body):
    players_in_door += 1
    if players_in_door >= 2:
        # end game code here

If bodies other than the player(s) can also enter the door area, you’d need to qualify what body entered / exited prior to changing the counter…

jgodfrey | 2023-06-25 15:47

Seems to be a very beginner programmer and the end function he want to call is attach to the player that’s why i use this approach but in fact yes there is much better way to check that.

zeludtnecniv | 2023-06-25 15:50