I am trying to move to using a state machine for my enemies in a 2D platformer. Setting up to have the enemy chase the player when they enter a detection zone, and go back to idle when the player leaves the detection zone. For some reason this has broke my statement for flipping the sprite. I've tried moving the code to the Chase state, and rewording the code to if direction >0 , or != 1, and a few other ways. No matter what I've tried, the sprite will not flip.

Can someone take a look at this and tell me what I am missing?

extends KinematicBody2D

const GRAVITY = 10
const FLOOR = Vector2(0, -1)


var velocity = Vector2()
var direction = -1
var knockback = Vector2.ZERO

export var ACELLERATION = 300
export var MAX_SPEED = 200



onready var stats = $Stats
onready var playerDetectionZone = $PlayerDetectionZone

enum {
	IDLE,
	 WANDER,
	 CHASE
}

var state = IDLE

func _ready():
	pass

func _physics_process(delta):
	
	match state:
		IDLE:
			velocity = velocity.move_toward(Vector2.ZERO, GRAVITY * delta)
			seek_player()
			$AnimatedSprite.play("Idle")
			velocity.x = 0
			
		WANDER:
			pass
			
		CHASE:
			var player = playerDetectionZone.player
			if player != null:
				var direction = (player.position - position).normalized()
				velocity = velocity.move_toward(direction * MAX_SPEED, ACELLERATION * delta)
				$AnimatedSprite.play("Run")
			lose_player()
			
			
	knockback = knockback.move_toward(Vector2.ZERO, 300 * delta)
	knockback = move_and_slide(knockback)
	
	if direction == 1:
		$AnimatedSprite.flip_h = true
	elif direction != 1:
		$AnimatedSprite.flip_h = false
	

	
	
	velocity.y += GRAVITY
	velocity = move_and_slide(velocity)
		


func _on_HurtBox_area_entered(area):
	stats.health -= 1
	knockback = Vector2(250,-300)
	$AnimatedSprite.modulate = Color(255, 0, 0, 1)
	print("Enemy health is ", stats.health)

func _on_Stats_no_health():
	queue_free()

func seek_player():
	if playerDetectionZone.can_see_player():
		state = CHASE
	
func lose_player():
	if !playerDetectionZone.can_see_player():
		state = IDLE


func _on_HurtBox_area_exited(area):
	$AnimatedSprite.modulate = Color(1, 1, 1, 1)
4 days later

Here's a snippet of the code I used. It flips my sprite just fine.

onready var _animated_sprite = $AnimatedSprite


func physics_process(delta): motion.y += gravity if Input.is_action_pressed("ui_right"): motion.x = speed / delta if is_on_floor(): animated_sprite.play("Walk") animated_sprite.flip_h = true #<---------- elif Input.is_action_pressed("ui_left"): motion.x = -speed / delta if is_on_floor(): animated_sprite.play("Walk") _animated_sprite.flip_h = false #<----------

Thank you, I finally figured it out. I had switched some wording around when adding the AI and I was using the same var for two different things. Just had to rename one. I appreciate your help :)

a year later