Wrong Animation being played

Godot Version

4.6.2

Question

I’m a begginner to the Godot engine and have gotten into making a 2d game, it has been going pretty well however i’ve ran into an issue while making an NPC. I used the DevWorm tutorial (https://www.youtube.com/watch?v=LMSbPkNgnWA) and modified his roaming script a bit.

extends CharacterBody2D
var dir = "down"
var state = "idle"
var is_chatting = false
var is_roaming = true
const speed = 30.0

func _ready():
	randomize()
	
func ChooseRandom(array):
	array.shuffle()
	return array.front()
	
func move():
	match dir:
		"left":
			velocity.x = -speed
		"right":
			velocity.x = speed
		"up":
			velocity.y = speed
		"down":
			velocity.y = -speed
			
func _physics_process(delta: float):
	if state == "move":
		if dir == "left":
			$AnimatedSprite2D.play("walkleft")
		elif dir == "right":
			$AnimatedSprite2D.play("walkright")
		elif dir == "up":
			$AnimatedSprite2D.play("walkback")
		elif dir == "down":
			$AnimatedSprite2D.play("walkfront")
	elif state == "idle" or "newdir":
		if dir == "left":
			$AnimatedSprite2D.play("idleleft")
		elif dir == "right":
			$AnimatedSprite2D.play("idleright")
		elif dir == "up":
			$AnimatedSprite2D.play("idleback")
		elif dir == "down":
			$AnimatedSprite2D.play("idlefront")
	
	if is_roaming:
		match state:
			"idle":
				print("idle")
				velocity.x = 0
				velocity.y = 0
				pass
			"move":
				print("move")
				move()
			"newdir":
				print("newdir")
				dir = ChooseRandom(["up", "right", "down", "left"])
				state = ChooseRandom(["idle", "move"])
				velocity.x = 0
				velocity.y = 0
	move_and_slide()
	
	
	


func _on_timer_timeout():
	state = ChooseRandom(["idle", "move", "newdir"])
	$Timer.wait_time = ChooseRandom([1, 2 , 2.5, 3, 3.5])
	print("timeout")

issue is that when it moves it plays the idle animation (not even in the right direction) instead of the walk animation, ive tried to fix it but i couldnt.

Yes, i have checked and verified the animations and made sure the animations are the right ones.

Thanks in advance to anyone who can help!

Are the walk animations all looping?

Error here … most progranming languages (and gdscript last time i checked) use something like:

elif ((state == "idle") or (state == "newdir")):

The compiler interprets what you have as

if A or B: and thats like if A or if B

so thats like if “newdir” != null: so thats like saying if non_null != null :

i dont know why that branch would execute first

2 Likes

Yes I’ve made this mistake too!

To avoid long lines filled of state == x or state == y or state ==… it’s possible to just write elif state in [“idle”, “newdir”]. Convenient

1 Like

Thank you! I fixed this however it still does not execute the right part! Sorry for the late response!