My idea is to make my enemy bite (attack) player whenever they are near each other. The function seem working great, but because I set the enemy's Animation Tree to look at player position in order to play the attack based on player position, of course. But the problem comes up whenever the player runs across the enemy, it will play the animation again and again because the player keep running.
My bad, I think it would be better if we look at the codes:
var is_attacking = false
func _physics_process(delta: float) -> void:
if is_dead == false:
knockback = knockback.move_toward(Vector2.ZERO, 200 * delta)
knockback = move_and_slide(knockback)
if is_hurt == false:
if is_attacking == false:
if _player != null:
state = MOVE
var direction = position.direction_to(player.global_position).normalized()
velocity = velocity.move_toward(direction * MAX_SPEED, ACCELERATION * delta)
if stop == true:
velocity = Vector2.ZERO
if _player == null:
state = IDLE
velocity = velocity.move_toward(Vector2.ZERO, FRICTION * delta)
if ! is_attacking && position.distance_to(player.global_position) < attack_distance:
is_attacking = true
if is_attacking == true:
state = ATTACK
velocity = Vector2.ZERO
$Sprite.visible = false
$Sprite2.visible = true
is_attacking = false
As you can see, like I said, the attack function will be called whenever the player is too close and play specific animations based on the player's location, but the problem will arise if the player run across the enemy. For instance, we have the player's opponent on the right is "a", down is "b" and left is "c". If the player is standing at the "a" position of the enemy, the right animation will be played and damage the player. But when the player is running around, the animation won't be lock and play both "b" and "c" too if he runs over those positions.
In this case, my enemy will play the right animation at the beginning of 0.2 secs ( the attack animation have 8 frames for 0.8 secs btw), then switch to down animation because the player run thought the "b" position for 0.2 secs and at the end, attack the player at the left position.
I hope that my summary does help you in order to understand the problem, and if it doesn't, please ask me if there are any crazy things that you haven't comprehended yet, I wouldn't mind to answer all of them, but please use kind words and of course, thanks for all the efforts and pardon me for my bad English.