Player gets pushed away when he get attacked by an enemy(knockback)

Godot Version

4.3

Question

so im making a metroidvania(platformer) and i also made enemies but i want that if enemies attack, you get pushed out of the way but i dont know how to code it.also i want that after the death animation, the player respawns at the position (260, 2000).can someone help me.btw here is my player code:

extends CharacterBody2D

@onready var anim: AnimatedSprite2D = $AnimatedSprite2D
@onready var gun: Node2D = $Gun

@export var SPEED : int = 300
var JUMP_VELOCITY : int
@export var jump_max : int

var jump_counter : int = 0
var health : int = 10
var is_not_damaged : bool = true

func _ready() → void:
jump_counter = jump_max
top_level = true
func _physics_process(delta: float) → void:
if is_not_damaged:
if Input.is_action_just_pressed(“attack”):
gun.shoot()

Handle jump.

if Input.is_action_just_pressed(“jump”):
jump_counter += 1
if jump_counter < jump_max:
JUMP_VELOCITY = -450
velocity.y = JUMP_VELOCITY

Get the input direction and handle the movement/deceleration.

As good practice, you should replace UI actions with custom gameplay actions.

var direction : float = Input.get_axis(“left”, “right”)

if Input.is_action_just_pressed(“left”):
anim.flip_h = true
if Input.is_action_just_pressed(“right”):
anim.flip_h = false

if is_on_floor():
jump_counter = 0
if direction > 0 or direction < 0:
anim.play(“run”)
if direction == 0:
anim.play(“idle”)

if anim.flip_h:
	gun.dir = -1
else:
	gun.dir = 1

else:
velocity += get_gravity() * delta
if velocity.y < 0:
anim.play(“jump”)
if velocity.y == 1:
anim.play(“mid-air”)
if velocity.y > 0:
anim.play(“falling”)

if is_on_ceiling():
	jump_counter = jump_max

if direction:
velocity.x = direction * SPEED
else:
velocity.x = move_toward(velocity.x, 0, SPEED)

move_and_slide()
func die():
is_not_damaged = false
print(“i’m dead”)
anim.play(“dead”)
gun.hide()
await get_tree().create_timer(2).timeout

func _on_hurt_box_area_entered(area: Area2D) → void:
if area.name == “DamageZone”:
if health > 0:
is_not_damaged = false
gun.hide()
health -= 1
anim.play(“damage”)
velocity.x = -1 * 30
print(health)
await get_tree().create_timer(0.3).timeout
gun.show()
is_not_damaged = true
if health == 0:
die()

if you know the answer, pls reply :speech_balloon: i will really appreciate it :smiley:

pfff!forget about it. i tried it by myself and it worked :tada:

Make sure to format your code pastes


Knockback is a common issue with the character body template, the player needs to accelerate towards their target SPEED rather than be set instantly to it.

Should change to something like this

const ACCELERATION = 1500

var target_velocity: Vector2 = direction * SPEED
velocity = velocity.move_toward(target_velocity, ACCELERATION * delta)
1 Like

i’ve already solved it by myself but thanks! so can other people know how to code it

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.