Knockback not working

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By ItzKillerTTV

Hello! I am facing another issue.
I am making a top-down camera sort of game in which enemies go towards the player. However, after creating the knockback mechanic I quickly found out that the enemy didn’t actually recieve any knockback. I am unsure on how to fix this so I hope someone more experienced than myself could help me solve this.

This is the code in (all characters can take knockback):

func take_damage(dam: int, dir: Vector2, force: int) -> void:
hp -= dam
velocity += dir * force

This is the code that makes the players weapon have a hitbox:

onready var dicesword_hitbox: Area2D = get_node("Dicesword/Node2D/AnimatedSprite/Hitbox")

This is the code that ads a knockback direction to the knockback:

func _process(_delta: float) -> void:
  dicesword.rotation = mouse_direction.angle()
  dicesword_hitbox.knockback_direction = mouse_direction

And this is the code from the enemy itself:

extends FiniteStateMachine
 func _init() -> void:
 func _ready() -> void:
    if state ==

   func _get_transition() -> int:
       match state:
		       if not animation_player.is_playing():
       return -1

   func _enter_state(_previous_state: int, new_state: int) -> void:
       match new_state:"melee_move")

Please send help.

:bust_in_silhouette: Reply From: BoxyLlama

There’s a number of things that could be going wrong. But there are ways to test your code to see where things are breaking.

The first question you should ask, Is the player not receiving the knockback or is the knockback force just not large enough to actually knock them back?

  • One way to test this, is using a print(velocity) just before applying it to your enemy. Is it changing at all, or remaining constant?

If the velocity is remaining constant:

  • Make sure you’re calling take_damage before you’re applying movement. I think it’s unlikely this is your problem though.

  • This could also be caused if you’re using += in take_damage but then elsewhere are setting the velocity using =. Make sure that your normal movement is being added too the velocity, and not replacing it.

  • This could be tested by doing a print(velocity) inside of take_damage and again just before applying it to your movement. If it’s printing 2 different velocities. Then something is resetting your velocity after the knockback is applied.

If the velocity is changing, but it’s not enough:

  • Try increasing the force you’re applying to velocity.