How to get characterbody2ds to run away from the player?

Godot Version

4.2.1

Question

I have a game where you collect fireflies and I want the fireflies to run away from the player when they are in a certain range. Is there a way to do this?

Just apply velocity to the fireflies in a direction away from the player.

How do you get the direction to the player?

Hello!

I think the easiest way will be the following:

  • Add a player variable to your firefly script
  • Add Area2D on your firefly that will be used to detect when “'player is in range”
  • Connect body_entered to a function that set the player variable with the body detected if it’s a player
  • on_physics_process () of your firefly:
    • if player is set :
      • set velocity at “-position.directionTo(player.position) * delta * speed” to set velocity in the oposite direction of the player
      • call move_and_slide
  • Connect body_exited of your area2D to unset player if it’s the player that leave the area

This way, when the player are in range, firefly will start to move in the opposite direction of the player. And stop doing it when player leaves the range.

That’s a basic movement, if you want your firefly to avoid obstacle and other thing it will be more complicated

What you’re probably looking for is “steering behaviors”. This is a generic term given to basic AI behaviors like flee (which is the specific behavior you’re looking for).

I also suggest you read the docs about Vector2 or Vector3.

1 Like