-- Moves playerToTeleport close to destinationPlayer, if possible. Returns wether or not the operation succeeded

function TeleportToPlayer.teleport(playerToTeleport: Player, destinationPlayer: Player, teleportDistance: number)
	teleportDistance = teleportDistance or DEFAULT_TELEPORT_DISTANCE

	local spawnPoint = TeleportToPlayer.getCharacterTeleportPoint(destinationPlayer.Character, teleportDistance)
	if not spawnPoint or not TeleportToPlayer.validate(playerToTeleport, destinationPlayer, spawnPoint) then
		return false
	end

	local rootPart = playerToTeleport.Character and playerToTeleport.Character:FindFirstChild("HumanoidRootPart")
	local humanoid = playerToTeleport.Character and playerToTeleport.Character:FindFirstChild("Humanoid")
	if not rootPart or not humanoid then
		return false
	end

	if humanoid.Sit then -- Un-sits the player, otherwise the seat will be moved as well
		humanoid.Sit = false
		humanoid.Seated:Wait() -- Humanoid.Seated fires when the player stands up, after the seat weld is removed
	end

	-- Inspired from https://developer.roblox.com/en-us/api-reference/property/Humanoid/HipHeight
	local rootPartHeight = humanoid.HipHeight + rootPart.Size.Y / 2
	if humanoid.RigType == Enum.HumanoidRigType.R6 then
		local leg = humanoid.Parent:FindFirstChild("Left Leg") or humanoid.Parent:FindFirstChild("Right Leg")
		if leg then
			rootPartHeight += leg.Size.Y
		end
	end

	rootPart.CFrame = spawnPoint + Vector3.new(0, rootPartHeight, 0)
	return true
end
