How to make enemy follow until a certain length from player

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

The enemy will follow the player until its in range to attack then stop following and attack.

:bust_in_silhouette: Reply From: Dlean Jeans

The basic algorithm is like this:

# follow.gd

onready var enemy = get_parent()
onready var player = enemy.player # reference to the player, up to you

func _physics_process(delta):

    var to_player = player.global_position - enemy.global_position
    var distance = to_player.length()
    var direction = to_player.normalize()

    if distance > attack_range:
        enemy.move_and_slide(direction * enemy.speed)
    else:
        enemy.attack()

Regarding your other question (How to Extend to multiple scripts), you should add this as a child of the enemy.

The result: The skeleton in my last Ludum Dare game
With a bit of modification you can also make them back off when the player comes close.

Thanks one more question if i dont have an attack area range like i only have a veiw range, how can i stop him? Is it the same just change the attack_range to a number?

Newby | 2019-02-08 23:56

Just replace attack_range with your view range or anything or any variable

Dlean Jeans | 2019-02-09 04:04

Would it be easy to transform this example to make an enemy flee from the player if within a range?

Erwin Broekhuis | 2019-08-22 22:39