- Edited
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)