Knockback for player and enemies

How to implement a knockback logic for player and enemies? Can someone help?

The simplest solution (good to start with). On your Enemy scene:

@export var knockback_resistance: float = 1
var knockback = Vector2.ZERO

func _physics_process(delta):
		# your normal direction/velocity calculation here
		# after you have your final velocity value, you just need to add knockback vector to it
		# move_toward will reduce knockback vector each frame/call by resistance amount, i.e. bring knockback to a stop
		knockback = knockback.move_toward(Vector2.ZERO, knockback_resistance)
		velocity += knockback * delta

		global_position += velocity

Then simply set the .knockback property on the enemy. For example, to push enemy away from player, you can do:

# direction_to returns a normalized vector, i.e. < 1 pixel, so you want to multiply that by how far you want enemy to be knocked back
enemy.knockback = player.global_position.direction_to(enemy.global_position) * 100
1 Like