I'm programming AI in a top-down game that will move randomly until the player gets too close with it (Using a separate CollisionShape2D). The enemy itself is a KinematicBody2D. This is what I have so far for its AI:
func _on_Detection_body_entered(body):
if body.is_in_group("player"):
if can_move == true:
for tinge in body:
if (tinge.get_global_pos().x < self.get_global_pos().x):
moveVec += Vector2(-1,0)
if (tinge.get_global_pos().x > self.get_global_pos().x):
moveVec += Vector2(1,0)
if (tinge.get_global_pos().y < self.get_global_pos().y):
moveVec += Vector2(0,-1)
if (tinge.get_global_pos().y > self.get_global_pos().y):
moveVec += Vector2(0,1)
func _on_MoveTimer_timeout():
if can_move == true:
$MoveTimer.wait_time = rand_range(2,6)
$MoveTimer.start()
facing = moves.keys()[randi()%4]
if facing == "right":
moveVec.x += rand_range(2,5)
if facing == "left":
moveVec.x += rand_range(-5,-2)
if facing == "up":
moveVec.y += rand_range(-5,-2)
if facing == "down":
moveVec.y += rand_range(5,2)
I'm using a timer called "MoveTimer" in order to make sure there are delays in between when the enemy changes direction. The MoveTimer's wait time is randomized. The enemy is supposed to move randomly until the player steps in its separate CollisionShape. Afterward it begins to chase the player. My problem is that the game crashes if they get too close instead. What do you suggest I do?