Getting knocked back in the correct direction

Having trouble figuring out how to code knockback direction when getting hit by an enemy.

Currently, the player only gets knocked back in the correct direction if the player is getting hit “face on” by the enemy. Although if the player gets hit in the back they get knocked toward the enemy instead.

Any and all help is appreciated

Code for knockback:

class_name hurtstate
extends Player_State
@export var fall_state : Player_State
@export var ground_state : Player_State
@export var hurt_animation : String = "Hurt"
@export var run_animation_node : String = "Run"
@export var fall_animation_node : String = "Fall"
@onready var timer: Timer = $Hurt_Timer

func knockback(force: float, x_pos: float, up_force: float):
	if (0 > character.latest_direction):
		character.velocity = Vector2(force * 2 * x_pos, -force * up_force)
		character.velocity = Vector2(-force * 2 * x_pos, -force * up_force)

func on_enter():

func state_process(delta):
	if (timer.is_stopped()):
		Game.hurt = false
		if (character.is_on_floor()):
			character.velocity = Vector2(0, 0)
			next_state = ground_state
		elif(character.is_on_floor() == false):
			character.velocity = Vector2(0, 0)
			next_state = fall_state

The simplest way to get the directions is use something like: (who_received_the_hit.global_position - who_applied_the_hit.global_position).normalized() this will give you the direction you should apply the knockback force

oh yeah, thanks a lot man :slight_smile:

Sorry for replying late, do you know how to go about doing that with a state machine?