extends Node2D


# Declare member variables here. Examples:
# var a: int = 2
# var b: String = "text"

var gridPos: Vector2 = Vector2(0,0)
var lastPos: Vector2 = Vector2(0,0)
var anim : float = 0.0

const ANIM_SPEED : float = 0.02

# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	gridPos = get_parent().world_to_map(position)
	

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
	var duration: float = (lastPos - gridPos).length() * ANIM_SPEED
	if (duration <= 0):
		anim = 1.0
	if (anim < 1.0):
		anim = min(anim + delta / duration, 1.0)
		
	position = get_parent().map_pos(lerp(lastPos,gridPos,anim))
	
func _input(event: InputEvent) -> void:
	if event.is_action_pressed("game_up"):
		move(Vector2(0,-1))
	elif event.is_action_pressed("game_up_left"):
		move(Vector2(-1,-1))
	elif event.is_action_pressed("game_left"):
		move(Vector2(-1,0))
	elif event.is_action_pressed("game_down_left"):
		move(Vector2(-1,1))
	elif event.is_action_pressed("game_down"):
		move(Vector2(0,1))
	elif event.is_action_pressed("game_down_right"):
		move(Vector2(1,1))
	elif event.is_action_pressed("game_right"):
		move(Vector2(1,0))
	elif event.is_action_pressed("game_up_right"):
		move(Vector2(1,-1))

func move(dir: Vector2):
	lastPos = gridPos
	gridPos = get_parent().find_move(gridPos,dir)
	anim = 0
	
