extends KinematicBody


# physics
var moveSpeed : float = 5.0

# cam look
var minLookAngle : float = -90.0
var maxLookAngle : float = 90.0
var lookSensitivity : float = 10.0

var ray: RayCast

# vectors
var vel : Vector3 = Vector3()
var mouseDelta : Vector2 = Vector2()

onready var camera : Camera = get_node("Camera")

func _ready():
	move_and_slide(Common.latLonToGlobal(0,0,1750), Vector3.UP)

func _process(delta):
	# rotate the camera along the x axis
	camera.rotation_degrees.x -= mouseDelta.y * lookSensitivity * delta
	
	# clamp camera x rotation axis
	camera.rotation_degrees.x = clamp(camera.rotation_degrees.x, minLookAngle, maxLookAngle)
	
	# rotate the player along their y-axis
	rotation_degrees.y -= mouseDelta.x * lookSensitivity * delta
	
	# reset the mouseDelta vector
	mouseDelta = Vector2()
	var origin = get_global_transform().origin
	.get_parent().get_node("UI/2").text="latlonhight: "+str(Common.globalToLatLon(origin.x,origin.y,origin.z, origin.length()))+","+str(origin.length())
 
func _input(event):
	if event is InputEventMouseMotion and Input.get_mouse_mode() == Input.MOUSE_MODE_CAPTURED:
		mouseDelta = event.relative

func _physics_process(delta):
 
	# reset the x and z velocity
	vel.x = 0
	vel.y = 0
	vel.z = 0
	
	var input = Vector3()
	
	# movement inputs
	if Input.is_action_pressed("move_forward"):
		input.y -= 1
	if Input.is_action_pressed("move_backward"):
		input.y += 1
	if Input.is_action_pressed("move_left"):
		input.x -= 1
	if Input.is_action_pressed("move_right"):
		input.x += 1
	if Input.is_action_pressed("move_up"):
		input.z += 1
	if Input.is_action_pressed("move_down"):
		input.z -= 1
		
	input = input.normalized()
	
	# get the forward and right directions
	var forward = global_transform.basis.z
	var right = global_transform.basis.x
	var up = global_transform.basis.y
	
	var relativeDir = (forward * input.y + right * input.x + up * input.z)
	
	var moveSpeed2 = moveSpeed
	if Input.is_action_pressed("sprint"):
		moveSpeed2 = moveSpeed * 3
	# set the velocity
	vel.x = relativeDir.x * moveSpeed2
	vel.z = relativeDir.z * moveSpeed2
	vel.y = relativeDir.y * moveSpeed2
	
	var gravity = self.global_transform.origin.normalized()
	# move the player
	vel = move_and_slide(vel, Vector3.UP)
	#ray = ray.look_at(self.global_transform.origin, Vector3.UP)
	
	var pos = self.global_transform.origin
	var polPos = Common.globalToLatLon(pos.x,pos.y,pos.z)
	var rotationDeg=get_rotation_degrees().x
	var posNorm=abs(pos.normalized().y)
	var targetRot = posNorm * 90
	#if rotationDeg < targetRot:
		#rotate_x(1)
	#elif rotationDeg > targetRot:
		#rotate_x(-1)
	
	.get_parent().get_node("UI/1").text="x:%s y:%s z:%s" %[pos.x, pos.y, pos.z]
	#.get_node("UI/3").text="LatLonPos=="+str(latLonToGlobal( self.global_transform.origin.x,self.global_transform.origin.y))
	
