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):
	deal_with_damage()
	
        #movement code 
	if player_chase:
		
		position += (player.position - position) / speed
		
		$AnimatedSprite2D.play("walk")
		
		if (player.position.x - position.x) < 0:
			$AnimatedSprite2D.flip_h = true
		else:
			$AnimatedSprite2D.flip_h = false
	else:
		$AnimatedSprite2D.play("idle")
# 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
			$take_damage_cooldown.start()
			can_take_damage = false
			print("slime health = ", health)
			if health <= 0:
				self.queue_free()
#the function for knockback that i got from the tutorial that does nothing
func knockback():
	var knockbackDirection = -velocity.normalized() * knockbackPower
	velocity = knockbackDirection
	move_and_slide()

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 !

  • xyz replied to this.

    buzzbuzz20xx It's praiseworthy that you're experimenting with adding new features that are not in the tutorial. But start with a simpler version of what you want to do - for example make the enemy stop for a second when they've been hit.

      xyz yeah i'll just resort to this if i can't figure the knock-back thing out haha

      • xyz replied to this.

        buzzbuzz20xx It's not about resorting to it. Making them stop is actually a simpler version of the knockback. So first try to implement a simpler version, and then gradually develop it into a more complex thing. That's generally an approach that works well with coding games, and coding in general for that matter.