How do I make my enemy (kinematicbody2d) move around randomly

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

I would really like to know how I can make my enemy (kinematicbody2d) move around randomly and also display the movement animations when it does so? I would also like to add an area2d to it so it detects the player and chases it. Here is scene tree and also the script for enemy which I made by following a YouTube video (it worked in the video):

Node2D
Ysort
^Skeleton(KinematicBody2D)
^ Skeleton(AnimatedSprite)
^ CollisonShape2D
^Player(KinematicBody2D)
^ icon(AnimatedSprite)
^ Camera2D
^ CollisionShape2D

extends KinematicBody2D

var speed = 100
var velocity = Vector2()
var state = 0
var rng = 0




func _process(delta):

    state = rand_range(0, 4)
    print(state)

if state == 0:
	pass
#Right
elif state == 1:
	velocity.x = speed
	$Skeleton.play("SWalkR")
#Left
elif state == 2:
	velocity.x = -speed
	$Skeleton.play("SWalkL")
#Forward
elif state == 3:
	velocity.y = speed
	$Skeleton.play("SWalkF")
#Back
elif state == 4:
	velocity.y = -speed
	$Skeleton.play("SWalkB")

how complicated do you want the movement to be? is there obstacles that the enemy needs to avoid?

Millard | 2020-09-28 18:12

Piggybacking on @Millard’s comment, what exactly do you mean by “random?” Do you want true randomness? Is it like a Wander AI? As Millard asked, are there obstacles that the character needs to steer away from? There’s a lot of details missing from the question that we need in order to best provide an answer.

jonbonazza | 2020-09-29 03:02

:bust_in_silhouette: Reply From: Moldor2

For 2D platformers: I like Gonkee’s tutorial, he shows how to have an AI enemy follow the player, and have it move around randomly if it can’t see the player.

For Top-down shooters: I found this tutorial series from jimbiv on youtube for a top-down shooter, he includes how to make an enemy AI and a patrol state as well, hope this helps you.

My game is top down so it doesn’t work as well :confused:

Amateur.game.dev. | 2020-09-28 15:58

Let me cook something up for you…

Moldor2 | 2020-09-29 12:15

Alright I watched through most of part 8 and 9 of his videos and they should have what you are looking for as well as the ability to do more with the concepts that he is teaching. I linked the whole 22 video playlist for you in my answer up top.

Moldor2 | 2020-09-29 12:20