Godot Version
4.2.2 stable Windows 11
Question
I have this hierarchy of extending scripts:
CharacterBody2D > enemy.gd > ai_fighter.gd > slime.gd
I tried to write some knockback code.
In enemy.gd:
@export var kb_recovery = 0.1
var kbdir = Vector2.ZERO
var totalkb = Vector2.ZERO
@onready var player = get_tree().get_first_node_in_group("player")
func take_damage(dmg, knockback) :
hp -= dmg
kbdir = player.global_position.direction_to(global_position)
totalkb = kbdir * knockback
In ai_fighter.gd:
func _physics_process(_delta):
var direction = global_position.direction_to(player.global_position)
totalkb.move_toward(Vector2.ZERO, kb_recovery)
print(totalkb)
velocity = direction*movement_speed
velocity += totalkb
move_and_slide()
This should make the enemies with this AI move towards the player at a constant speed, and when they take damage theyre pushed away from the player and gradually regain their pace. However, whenever they take damage, totalkb stays the same forever - they keep the knockback momentum and never recover, and the output console prints the same value on every frame. Everything else runs fine.
From what I can gather, everything here is fine, except the function totalkb.move_toward(Vector2.ZERO, kbrecovery) isn’t doing anything. I have no idea why this is happening. I made sure there is only one _physics_process function in the script chain.
Can anyone tell me what I’m doing wrong? How do I make this work? Any help is appreciated.