i was following a tutorial series on YouTube on creating a Zelda clone in Godot 4.2.1 and everything works fine, but the tutorial never implements a knock-back effect when attacking an enemy so i wanted to implement that myself

i tried using this tutorial video but it obviously didn't work since the way the enemy movement is coded in my game is different from this tutorial

here's my Code for the enemy

func _physics_process(delta):
        #movement code 
    if player_chase:
        position += (player.position - position) / speed
        if (player.position.x - position.x) < 0:
            $AnimatedSprite2D.flip_h = true
            $AnimatedSprite2D.flip_h = false
# function for dealing with getting hit by the player
func deal_with_damage():
    if player_inattack_area and global.player_current_attack == true:
        if can_take_damage == true:
            knockback() #here i tried calling the knockback function but nothing happens
            health = health - 20
            can_take_damage = false
            print("slime health = ", health)
            if health <= 0:
#the function for knockback that i got from the tutorial that does nothing
func knockback():
    var knockbackDirection = -velocity.normalized() * knockbackPower
    velocity = knockbackDirection

so yeah no knockback happens because my enemy moves by simply changing it's position to chase the Player, no velocity is ever used in the movement code, how can i implement the knockback effect with my current code ? or should i change my code entirely ? I appreciate any help !


1 Answer 1


I can see that the issue with the movement comes from moving the enemy both with move_and_slide() and directly setting the enemy position in each frame.

For CharacterBody2D (I'm assuming it's a CharacterBody2D because of move_and_slide()), the recommended way to move is to call move_and_slide() every physics frame, because it will deal with frame speed, collisions and moving platforms for you.

So you will need to change the code to set velocity instead of setting the position in the line position += (player.position - position) / speed. Then, you need to call move_and_slide() once in _physics_process. No need to call it again in knockback().

You will also need to set a timer after taking damage before the enemy can move again, because the movement speed will override the knockback speed.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .