extends CharacterBody3D

# Member variables
var walk_speed = 1.0

var g = -9.8
const MAX_SPEED = 5
const JUMP_SPEED = 7
const ACCEL= 8
const DEACCEL= 8
const MAX_SLOPE_ANGLE = 30

@onready
var camera = $CSGMesh3D/Camera3D


func _physics_process(delta):
	var dir = Vector3() # Where does the player intend to walk to
	var cam_xform = camera.get_global_transform()

	if Input.is_action_pressed("move_forward"):
		dir += -cam_xform.basis[2]
	if Input.is_action_pressed("move_backwards"):
		dir += cam_xform.basis[2]
	if Input.is_action_pressed("move_left"):
		dir += -cam_xform.basis[0]
	if Input.is_action_pressed("move_right"):
		dir += cam_xform.basis[0]

	dir.y = 0
	dir = dir.normalized()

	velocity.y += delta * g

	var hvel = velocity
	hvel.y = 0

	var target = dir * MAX_SPEED
	var accel
	if dir.dot(hvel) > 0:
		accel = ACCEL
	else:
		accel = DEACCEL

	hvel = hvel.lerp(target, accel * delta)

	velocity.x = hvel.x
	velocity.z = hvel.z

	move_and_slide()

	if is_on_floor() and Input.is_action_pressed("jump"):
		velocity.y = JUMP_SPEED


func _on_tcube_body_enter(body):
	if body == self:
		get_node("../ty").show()

# accumulators
var rot_x = 0
var rot_y = 0

func _input(event):
	if event is InputEventMouseMotion and event.button_mask & 2:
		# modify accumulated mouse rotation
		rot_x -= event.relative.x * 0.005
		rot_y -= event.relative.y * 0.005
		camera.transform.basis = Basis() # reset rotation
		camera.rotate_object_local(Vector3(0, 1, 0), rot_x) # first rotate in Y
		camera.rotate_object_local(Vector3(1, 0, 0), rot_y) # then rotate in X
		
	if event.is_action_pressed("interact"):
		var space_state = get_world_3d().direct_space_state
		# use global coordinates, not local to node
		print(camera.basis)
		var query = PhysicsRayQueryParameters3D.create(camera.position, camera.position + camera.basis.z * 2.0)
		var result = space_state.intersect_ray(query)
		print(result)
