0 votes

I have a large number of units which follow a path like a tower defense and this all works well i am using set_pos() to have them follow the path; however i would also like them to not overlap eachother (i was thinking add an impulse when there is a collision but it does not work the way i did it) like they do currently they are rigidbody2D i am hoping there is an easy way to handle this. if i need to use a different body that works too just would like to know

thanks

Edit: just add the code im using to follow path

func update_path():
    path = nav.get_simple_path(get_pos(), goal, false)
    if path.size() == 0:
        queue_free()

func _fixed_process(delta):
    if path.size() > 1:
        var d = get_pos().distance_to(path[0])
        if d > 2:
            set_pos(get_pos().linear_interpolate(path[0], (speed * delta)/d))
        else:
            path.remove(0)
    else:
        queue_free()
in Engine by (20 points)
edited by

1 Answer

+2 votes
Best answer

If you want it to look good, you need to implement some kind of steering behavior to your units. The unit will "want" to follow the path, but also "want" to avoid nearby units. The classic use of this is "flocking" behavior, which is used to simulate all sorts of crowd-like movements.

The code required is remarkably simple. You have a "steering force" pushing the unit towards the path, and an other, smaller force pushing away from each nearby unit. Sum up the forces, and you have a resulting movement vector for the unit.

This book is the bible for implementing such things - I highly recommend checking it out:
http://natureofcode.com/book/chapter-6-autonomous-agents/

by (21,577 points)
selected by

ok, ill look into it and ill post code here when i figure it out, should i be using rigidbody2D? the only functionality i want is if the units come into range of certain building to change the path to another. I feel like rigid is probably not needed, also love your youtube videos they are pretty great. you probably noticed the code snipet is from your tutorial :D

What type of body really depends on the rest of your setup, but i general, you usually don't need a RigidBody2D. KinematicBody2D will be sufficient, you have a movement vector (ie velocity) and you pass that to move()

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.