Timer never start

Godot Version

<stable4.2>

Question

<Im using enum state to make enemy for my 2d platformer project. Id like to change enemy state after timer timeout however, timer never starts. I believe this is because timer starts every frame. but i exactly would I have function to manage state changes and only change the state if it does not match the current state?

enum States {IDLE, CHARGE, RUSH, SHOOT, DEATH}
@onready var state: States = States.IDLE

func _ready():
	pass

func _physics_process(delta):
	$Label.set_text(States.keys()[state])
	match state:
		States.IDLE:
			$AnimationPlayer.play("idle")
			if direction == 1:
				$Marker2D.scale.x = -1
			elif direction == -1:
				$Marker2D.scale.x = 1
			velocity.x = 0
			velocity.y = gravity * delta
			shoot_count = 3
			move_and_slide()
			$Timer.start()
			#await get_tree().create_timer(5.0).timeout
			#if state == States.IDLE:
				#change_state_randomly01()

		States.CHARGE:
			$AnimationPlayer.play("charge")
			velocity.x = charge_speed * -direction
			charge_speed *= 0.97
			velocity.y = gravity * delta
			move_and_slide()

		States.RUSH:
			$AnimationPlayer.play("rush")
			charge_speed = initial_charge_speed
			if direction == 1:
				$Marker2D.scale.x = -1
			elif direction == -1:
				$Marker2D.scale.x = 1
			velocity.x = rush_speed * direction
			velocity.y = gravity * delta
			move_and_slide()
			if is_on_wall():
				Autoload.camera.shake(0.1, 1.5)
				direction *= -1
				wallhit_count += 1
			if wallhit_count >= max_wallhit:
				stop_at_nearest_position()

		States.SHOOT:
			$AnimationPlayer.play("shoot")
			velocity.x = 0
			velocity.y = gravity * delta
			move_and_slide()
			if shoot_count == 0.0:
				state = States.IDLE

func _on_timer_timeout():
	if state == States.IDLE:
		change_state_randomly01()
		print("TIMEOUT")

Check if the timer is already running before (re)starting it. Or create a queue of timers to run if you need your npc to perform one action after another.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.