Godot Version
4.3
Question
Hi I’m trying to make a simple steering system for a top down 2D game and I would like to know if anyone knows a way to make a character body 2D head towards one point while keeping a certain distance away from another?
4.3
Hi I’m trying to make a simple steering system for a top down 2D game and I would like to know if anyone knows a way to make a character body 2D head towards one point while keeping a certain distance away from another?
Hi!
I guess a simple way of doing that is computing a direction vector in multiple steps. You have a target that your character is moving towards, so you can initialize your direction vector using it:
(I’m writing “pseudo” code just to give you an idea of what I have in mind.)
var direction: Vector2 = target.position - character.position
Then, you need to consider any target your character needs to steer clear of. Let’s say you have only one, and if you someday have many targets you want to move away from, just use a loop.
Considering you have some steer_distance
variable, defining a radius around your character so that it starts the steering behaviour, this would be something like this:
var direction: Vector2 = target.position - character.position
if (steer_target.position - character.position).length < steer_distance:
direction += character.position - steer_target.position
Now, you may have strange results depending on the distances, so, to be able to control the feeling of the movement, add some values to control the intensity of the steering. You can also change the intensity based on the distance, normalize the vector before applying it, or anything else, it’s up to you.
For instance:
var direction: Vector2 = target.position - character.position
if (steer_target.position - character.position).length < steer_distance:
direction += (character.position - steer_target.position) * steer_intensity
Finally, you just have to normalize your vector, multiply it by some movement speed, and apply it to the character (which, I guess, you know how to do already).
var direction: Vector2 = target.position - character.position
if (steer_target.position - character.position).length < steer_distance:
direction += (character.position - steer_target.position) * steer_intensity
character.velocity = direction.normalize() * movement_speed
character.move_and_slide()
–
I suppose something like this would work.
A few years ago, I did watch this serie of video about implementing a flocking algorithm, and it’s really well made (clear and straight to the point). I’ve linked the part about steering but you can have a look at all the videos if you’re interested (I know you did not mention a complete flock behaviour and that the video author is using Unity, but there may be some cool concepts to learn still).
Let me know if that helps!
Thank you I’ll see if this works!