global_position.direction_to isn't working

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

I’m creating a flying enemy (kinematicbody2d) that swoops down to the player, then returns to its idle position. The code for going towards the player is this:

vel = global_position.direction_to(frozenTarget) * attackSpeed
vel = move_and_slide(vel)

frozenTarget is simply a snapshot of the player’s global_position, saved every frame, and not updated once the above code starts running. This code works great, flies to the target perfectly. The problem is when I try to return to the idle target using this:

vel = global_position.direction_to(target.global_position) * idleSpeed
vel = move_and_slide(vel)

This code is what’s failing. The target variable is an area2d node which is defined in the editor and represents the idle position for the enemy. I’ve made sure that its position and global_position are the same, and that it is in fact where I want it in the editor.

When I place the target idle position to the right of the player it generates this vel (printed vel between getting the direction and applying with moveandslide)

(148.974014, -17.514053)

This seems to line up with what I placed in the editor, being far to the right and slightly up. However, the enemy does not return to that target position, they in fact go just slightly above that position. What could be causing this? Is it possible I’m just using the function wrong?

Please let me know if I left out any crucial details by mistake. Thanks!

:bust_in_silhouette: Reply From: Inces

So is direction correct or not ? Because what is failing in the end is final position. It doesn’t necessarily mean, that setting movement direction failed. What about the code to stop the movement ? Maybe it can’t cope with idlespeed and stops too late ?

:bust_in_silhouette: Reply From: SneakySteve

As it turns out I had an old bit of legacy code that was still running which slightly updated the vel.x values every frame. After removing this code the problem was fixed, entirely my own error.