I've been making a FPS in Godot and I'm having a hard time getting the kinematic body (the enemy) to go towards the player. Could someone please help?
1 Answers
The simplest way to do this is to get the player's position, compare it to the enemy position, and make the enemy move towards it every frame.
Full example code is at the bottom.
To get the player's position you first need a reference to it. You can usually do this through storing the reference in global singleton (autoload) or by exposing a public property.
If you are doing it with a global singleton, then you get the position by calling
var player_position = my_singleton.player.global_transform.origin
If you are using an exported property, then you would get the position by calling
var player_position = get_node(path_to_player).global_transform.origin
Once you have the player position, you can compare it to the enemy by writing
var direction_to_target = player_position - global_transform.origin
from inside the enemy node.Now in order to follow the player, we override the
_physics_process
method with something like this:
### Inside the enemy script
var ENEMY_SPEED= 50
func _physics_process(delta):
var player_position = my_singleton.player.global_transform.origin
var direction_to_target = (player_position - global_transform.origin).normalized() # We normalize the vector because we only care about the direction
move_and_slide(direction_to_target * ENEMY_SPEED) # We multiply the direction by the speed