I am making 2D platformer zombie shooting game. I implemented zombie enemy which can grab and hold player when collided with player. As soon as zombie enemy collided with player, zombie enemy will start GRAB STATE, and plays grabbing animation. On the other hand, Player when collided with zombie enemy, its sprite will be invisible, movement and control will be disabled. While player is being grabbed by zombie, player can escape from zombie by smashing the button. (GIF01)
All of this sequences works completely fine when there is only one enemy spawned on the platform. However, when I duplicated zombie enemy and spawned several of them, problem occurs. That is, when zombie A and zombie A(duplicated one) collided with player at the exact same time, they both start GRAB STATE. (GIF02)
How exactly do I avoid this problem?
You need to condition the enemy's state change on whether it's currently possible to grab the player or not.
In the player script, you can give it a variable like var can_be_grabbed = true
In the zombie script, I assume you have a reference to the player node. E.g.
onready var player = get_node("path_to_player")
Then, the zombie states will be something like:
match state:
IDLE_STATE:
if overlaps_body(player) and player.can_be_grabbed:
player.can_be_grabbed = false
state = GRAB_STATE
GRAB_STATE:
// Button smash code
if button_smash_complete:
player.can_be_grabbed = true
// Destroy the zombie