0

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?

SolerG0d
  • 11
  • 1

1 Answers1

0

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.

  1. 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

  2. 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.

  3. 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