Skip to content

Instantly share code, notes, and snippets.

@shackra
Created February 14, 2018 05:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shackra/38cd08c6dba8cdc09bb7bee1cf16e0de to your computer and use it in GitHub Desktop.
Save shackra/38cd08c6dba8cdc09bb7bee1cf16e0de to your computer and use it in GitHub Desktop.
FSM and Orientation
extends KinematicBody2D
enum ORIENTATION {
UP,
DOWN,
LEFT,
RIGHT
}
enum STATES {
WALK,
RUN,
IDLE
}
var current_state = null
var orientation = DOWN
var input_direction = Vector2()
var last_direction = Vector2(1, 0)
const MAX_WALK_SPEED = 400
const MAX_RUN_SPEED = 700
var speed = 0.0
var max_speed = 0.0
var velocity = Vector2()
func change_direction(direction):
if direction.y == -1:
orientation = UP
if direction.y == 1:
orientation = DOWN
if direction.x == 1:
orientation = RIGHT
if direction.x == -1:
orientation = LEFT
change_state(current_state)
func change_state(state):
current_state = state
match current_state:
IDLE:
match orientation:
UP:
$AnimationPlayer.play('idle up')
DOWN:
$AnimationPlayer.play('idle down')
LEFT:
$AnimationPlayer.play("idle left")
RIGHT:
$AnimationPlayer.play("idle right")
WALK:
match orientation:
UP:
$AnimationPlayer.play('walk up')
DOWN:
$AnimationPlayer.play('walk down')
LEFT:
$AnimationPlayer.play("walk left")
RIGHT:
$AnimationPlayer.play("walk right")
RUN:
match orientation:
UP:
$AnimationPlayer.play('walk up')
DOWN:
$AnimationPlayer.play('walk down')
LEFT:
$AnimationPlayer.play("walk left")
RIGHT:
$AnimationPlayer.play("walk right")
func _physics_process(delta):
update_direction()
move(delta)
func update_direction():
if input_direction and last_direction != input_direction:
last_direction = input_direction
change_direction(input_direction)
func move(delta):
if input_direction:
if speed != max_speed:
speed = max_speed
change_state(WALK)
$Label.text = "WALK"
else:
speed = 0
change_state(IDLE)
$Label.text = "IDLE"
velocity = input_direction.normalized() * speed
move_and_slide(velocity)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment