0 votes

The idea is that i need an entity that moves to the random point around it, waits for several secondss, repeats the process. But in this example entity moves constantly without delay. I tried many things but when I managed to add wait time I somehow broke the isattarget_position function.

enum {
    IDLE,
    WANDER
}

var velocity = Vector2.ZERO
var state = IDLE

const ACCELERATION = 300
const MAX_SPEED = 50
const TOLERANCE = 4.0

onready var start_position = global_position
onready var target_position = global_position

func update_target_position():
    var target_vector = Vector2(rand_range(-32, 32), rand_range(-32, 32))
    target_position = start_position + target_vector

func is_at_target_position(): 
    # Stop moving when at target +/- tolerance
    return (target_position - global_position).length() < TOLERANCE

func _physics_process(delta):
    match state:
        IDLE:
            state = WANDER
            # Maybe wait for X seconds with a timer before moving on
            update_target_position()

        WANDER:
            accelerate_to_point(target_position, ACCELERATION * delta)

            if is_at_target_position():
                state = IDLE

    velocity = move_and_slide(velocity)

func accelerate_to_point(point, acceleration_scalar):
    var direction = (point - global_position).normalized()
    var acceleration_vector = direction * acceleration_scalar
    accelerate(acceleration_vector)

func accelerate(acceleration_vector):
    velocity += acceleration_vector
    velocity = velocity.clamped(MAX_SPEED)
Godot version 3.3.3
related to an answer for: Making an ai that randomly moves
in Engine by (12 points)
edited by

1 Answer

0 votes

Difficult to say without seeing your code to tell you how it broke the is_at_target_position function you have.

I would suggest that you create a boolean set it to false and when you create a timer set it to true. Once the timer is over just link the timer to a new function which turns the boolean to false again. Then in your wait function you can have a simple if clause to ask if the boolean is true or false and only allow movement if it is false.

by (2,139 points)

My code is just a copy from a related answer. Anyway I understood you suggestion but it requiers major changes and my goal was slightly extend what I have so I will leave it for later.

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.