0 votes

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!

Godot version v3.4.2.stable
in Engine by (59 points)

2 Answers

0 votes
Best answer

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.

by (59 points)
0 votes

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 ?

by (7,743 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.