0 votes

How do you make an object under path2d/pathfollow to go in random directions, right now the object only goes at the direction the points were assigned

in Engine by (117 points)

1 Answer

+1 vote

If you want to go in random directions, PathFollow is not what you are looking for.
You can eventually offset the points from code, but it would be impractical if you want your node to truly go completely random.

Going at random directions is a procedural behaviour, so it requires a bit of scripting.

Here is an example of script that makes a node move in random directions. It's only one way of doing it, there is a plethora of ways depending on what you really want for your game:

extends Node2D

var speed = 60
var angular_speed = 0
var _angle_change_timer = null


func _ready():
    # Create a timer to make the node change directions regularly
    _angle_change_timer = Timer.new()
    _angle_change_timer.set_wait_time(0.5)
    _angle_change_timer.set_one_shot(false)
    _angle_change_timer.connect("timeout", self, "_change_direction")
    add_child(_angle_change_timer)
    _angle_change_timer.start()

    _change_direction()

    set_fixed_process(true)


func _fixed_process(delta):
    # Rotate
    set_rot(get_rot() + angular_speed * delta)
    # Move
    var forward = angle_to_direction(get_rot())
    set_pos(get_pos() + forward * speed * delta)


func _change_direction():
    angular_speed = rand_range(-PI, PI)


static func angle_to_direction(angle):
    return Vector2(cos(angle), -sin(angle))

Another way is to regularly choose random positions in an area and head to these positions, it's kinda the same logic.

by (28,735 points)

I tried ai with areas, but it turned out to be a disaster, so do I try the script inside the path2d node or do I make another node with the object under it

You can't use Path2D or PathFollow if you want your object to move randomly. For that you need to use a script. You don't need a specific node, but the one you want to move must at least inherit Node2D.

After that... it really depends on how you want to make it move, because there are many, many ways of "moving something at random".

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 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 webmaster@godotengine.org with your username.