Distance constraints for Charecter Body 2D

Godot Version

Godot 4.3

Question

How could I get one object (Character Body 2D) to follow another (Character Body 2D) object while staying a set distance away from it?

The game I am working on is a top down rpg type game kind of like the early Zelda games.

try this:

extends CharacterBody2D

@export var target: CharacterBody2D
@export var follow_speed: float = 100.0
@export var follow_distance: float = 50.0

func _physics_process(delta):
if target:
var direction = target.global_position - global_position
var distance = direction.length()

    if distance > follow_distance:
        direction = direction.normalized()
        velocity = direction * follow_speed
    else:
        velocity = Vector2.ZERO
    
    move_and_slide()

###EXPLANATION

the target is the object to follow,the follow speed is the speed of the follower(enemy).and the follow_distance is the desired distance to mantain.
The follower(enemy) moves towards the target only if it’s farther than follow_distance.

if you want that the enemy follows you while being closer(touching) to the follow_distance, just remove the if statement " if distance > follow_distance:" at line 12

1 Like

Thank you

If this works please mark the message above (The solution) as “solution” please. It helps make everything neat and we know what is and isn’t solved!

I will