extends KinematicBody



enum DIRECTIONS {NONE, UP, DOWN, LEFT, RIGHT}
var direction = null
var last_position = Vector3()
var target_position = Vector3()
var movedir = Vector3()
var tile_size = 2
var position_without_height = Vector3()
var was_on_ground = true

onready var ray_side = $RayCastSide
onready var ray_ground = $RayCastGround
onready var mesh_instance = $MeshInstance

export var speed = 7.5

export var roll_speed = 0
const DEACCELATION = 0.3
const GRAVITY = -10





func _ready():
	direction = DIRECTIONS.NONE
	translation = translation.snapped(Vector3(tile_size, tile_size, tile_size))
	last_position = Vector3(translation.x, 0, translation.z)
	target_position = Vector3(translation.x, 0, translation.z)
	#print ("init - x: " + String(translation.x) + ", y: " + String(translation.y) + ", z:"  + String(translation.z))
	

func get_movedir():
	
	if direction == DIRECTIONS.UP:	
		movedir = Vector3(0, 0, -1)
	elif direction == DIRECTIONS.DOWN:	
		movedir = Vector3(0, 0, 1)
	elif direction == DIRECTIONS.LEFT:	
		movedir = Vector3(-1, 0, 0)
	elif direction == DIRECTIONS.RIGHT:
		movedir = Vector3(1, 0, 0)
	else:
		movedir = Vector3(0, 0, 0)
	
	if direction != DIRECTIONS.NONE:
		ray_side.cast_to = movedir
	
func move(delta):

	position_without_height = Vector3(translation.x, 0, translation.z)
	
	if !ray_ground.is_colliding() and !was_on_ground:
		translation.y += GRAVITY  * delta
		
	was_on_ground = ray_ground.is_colliding()
	
	#		
	#			print ("push!!!!!!!!!!!!!!!!!")
	#			collidingObject.push(direction)
	if ray_side.is_colliding():
		
		position_without_height = Vector3(last_position.x, 0, last_position.z)
		target_position = Vector3(last_position.x, 0, last_position.z)

		
	else:
		position_without_height += speed * movedir * delta

		if position_without_height.distance_to(Vector3(last_position.x, 0, last_position.z)) >= tile_size - speed * delta:
			position_without_height = target_position
					
	if position_without_height == target_position:
		get_movedir()
		last_position = position_without_height
		target_position += movedir * tile_size
		#print ("x: " + String(translation.x) + ", y: " + String(translation.y) + ", z:"  + String(translation.z))
			
	translation.x = position_without_height.x
	translation.z = position_without_height.z
		
func roll(delta):
	#print ("???")
	if roll_speed == 0:
		print ("not rolling")
		return
	print ("rolling")
	
	if last_position.x > translation.x:
		mesh_instance.rotate_z(deg2rad(roll_speed) * delta)
	elif last_position.x < translation.x:
		mesh_instance.rotate_z(-deg2rad(roll_speed) * delta)
	elif last_position.z > translation.z:
		mesh_instance.rotate_x(-deg2rad(roll_speed) * delta)
	elif last_position.z < translation.z:
		mesh_instance.rotate_x(deg2rad(roll_speed) * delta)


	
func _physics_process(delta):
	
	
	move(delta)
	roll(delta)
	
	
	

 