Vector2 move_toward having no effect inside _physics_process

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.

your

totalkb.move_toward(Vector2.ZERO, kb_recovery)
should be something like
totalkb = totalkb.move_toward(Vector2.ZERO, kb_recovery)

move_toward doesnt actually change the vector, just returns a new changed copy of it

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