- Edited
So im new to Godot and trying to make a basic enemy. I'm trying to give it a wandering and chase state by making an area2d and using on_alert_body_entered/exited to change between the two states. That works just fine, however after a few moments or if I stop moving while in the area of the enemy, the game freezes. the movement code for both the player and enemy works perfectly fine, and if i remove the on body enter i have zero issues. also, if i never enter the enemy area, it also works fine
Heres a video showing this, if you need a visual:
i am completely stumped as to what im doing wrong. please help
i am using godot 4.0 on windows, if that's relevant
code(i don't know how to format this help):
`
extends CharacterBody2D
@onready var sprite=$AnimatedSprite2D
const movespeed = 100
const chasespeed = 200
var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")
var state = "Wander"
var direction = 0
var HP = 3
# Called when the node enters the scene tree for the first time.
func _ready():
while true:
if state=="Wander":
await get_tree().create_timer(2).timeout
direction= randi_range(-1, 1)
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(_delta):
if velocity.x > 0:
sprite.flip_h = true
elif velocity.x < 0:
sprite.flip_h = false
if HP<=0:
queue_free()
if state == "Wander":
print("Wander")
elif state == "Chase":
print("Chase")
func _physics_process(delta):
velocity.y += gravity * delta #gravity
if state=="Wander":
velocity.x = direction * movespeed
if state == "Chase":
velocity.x = direction * movespeed
move_and_slide()
func _on_alert_body_entered(body):
if body.name=="CharacterBody2D":
state="Chase"
func _on_alert_body_exited(body):
if body.name=="CharacterBody2D":
state="Wander"
`