AI movement help

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Forward

Trying to get my enemy AI to kind of just simply walk randomly in a direction around an area every time the timer goes off. When they move though they move in the direction, but will shake violently while doing so.

Any pointers or tips would be helpful! I’m definitely missing something in my logic I just can’t seem to figure out what…

func _process(delta):
	if(AI_STATE == AI_IDLE && can_Move ==true):
		AI_IDLE()
	if(AI_STATE == AI_CHASE && can_Move ==true):
		AI_CHASE()
	if(is_colliding()):
			slide()

func _on_move_Timer_timeout():
if(can_Move == false):
	can_Move = true
else:
	can_Move = false

func random():
	randomize()
	return randi()%2
	
func AI_IDLE():
	var atpos = Vector2(Vector2(random(),random()))
	atpos = atpos.normalized() * 2 
	move(atpos)

Is this the kind of behavior you are trying to implement?

Random Movement

Beamer159 | 2018-02-16 22:12

Yes, that is exactly what I’m trying to do! Any idea what I’m doing wrong? My KinematicBody2D shakes like crazy while it is in motion.

Forward | 2018-02-16 22:56

I altered the code a bit:

var direction = Vector2(0, 0)

func _process(delta):
    if(AI_STATE == AI_IDLE && can_Move ==true):
        AI_IDLE()
    if(AI_STATE == AI_CHASE && can_Move ==true):
        AI_CHASE()

func _on_move_Timer_timeout():
    if(can_Move == false):
        can_Move = true
        direction = Vector2(random(), random()).normalized() * 50
    else:
        can_Move = false

func random():
    randomize()
    return randi()%21 - 10 # range is -10 to 10

func AI_IDLE():
    move_and_slide(direction)

The most important change is that you should have a “direction” variable that gets updated only when the Timer timeouts. The code you posted looks like it updates the direction every time _process(…) is called, which could cause the jitters you experienced.

Beamer159 | 2018-02-16 23:16

Thank you so much! This fixed the problem and I understand what the heck I was doing wrong!

Forward | 2018-02-17 02:10