How to make an enemy go directly to the player?

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

Let’s say the player’s global_position is (0,0) and the enemy’s global position is (1000,1000) (both of them are KinematicBody2ds). Is there a way to make it take, let’s say 10 seconds, for the enemy to go directly at the player in a straight line? Thanks.

Does your enemy already have access to the player node? If so you can do

velocity = move_and_slide((distanceToPlayer/timeToReachPlayer) * global_position.direction_to(playernode.global_position).normalized())

Inside of the enemy’s physics process function (pseudo-code above). You could simplify that based on the context of the game (maybe you don’t need to recalculate the direction to the player every physics frame)

Lerping or linear interpolation might work, but you should only move kinematic bodies using move and slide or move and collide, etc

If your enemy does not know how to access the player node’s position then I have some ideas

BigTuna675 | 2022-10-07 20:34

It does have access the player node. Thanks for the answer.

shifitzel | 2022-10-07 21:09

Just wondering, is there a way to make it go at a set speed like 600 positions instead of a set time? Thanks.

shifitzel | 2022-10-08 23:57

:bust_in_silhouette: Reply From: TechShubham

You can get help from this tutorial-:

Thank you for the video.

shifitzel | 2022-10-13 19:01