How to count collision and make characterbody2d stop at position2d

Godot Version

<4.2 >

Question

<Im trying to recreate squid baron boss spinning attack from shantae in godot. looking at video, it seems that boss always stop at two fixed positions after hitting the wall three times. what i want to know here is how to count how many times characterbody2d hit the wall, and how to stop characterbody2d at position2d(placed in level scene) after certain count.>

Like you count anything, really: By declaring a variable and increasing it, once a certain condition is met.

In this case, that condition would be contact with the wall, which you can detect by using the CharacterBody2D’s function is_on_wall(). Just make sure that you call it after calling move_and_slide and that you invert the direction right away (so the boss will immediately move away from the wall next frame).

You can use direction_to() to figure out in which direction to move, and distance_to() will tell you how far you have to move:

var direction : Vector2 = global_position.direction_to(target_position)
var distance : float = global_position.distance_to(target_position)

Then just modify your velocity vector accordingly.