-- This module can be required and used by other scripts to get information about where the mouse is in the 3D world
local module = {}

local input = game:GetService("UserInputService")
module.mouseDistance = 500
module.mouseRaycastParameters = RaycastParams.new()

local dominantFinger
local usingMouse = true
local lastMouseInstance
local lastMouseRay

game:GetService("UserInputService").TouchStarted:Connect(function(touch,irrelevant)
	if not irrelevant and not dominantFinger then
		dominantFinger = touch
		usingMouse = false
	end
end)
game:GetService("UserInputService").TouchEnded:Connect(function(touch,irrelevant)
	if touch == dominantFinger then dominantFinger = nil end
end)
local uit = Enum.UserInputType
local mouseInputs = {uit.MouseButton1,uit.MouseWheel,uit.MouseMovement,uit.MouseButton2}
for _,item in ipairs(mouseInputs) do mouseInputs[item] = true end
game:GetService("UserInputService").InputBegan:Connect(function(object)
	if mouseInputs[object.UserInputType] then usingMouse = true end
end)

function module.getMouseHit(location)
	local mousePosition = location or input:GetMouseLocation()
	local mouseRay = game.Workspace.CurrentCamera:ViewportPointToRay(mousePosition.X,mousePosition.Y)
	if dominantFinger then
		local position = dominantFinger.Position
		mouseRay = game.Workspace.CurrentCamera:ScreenPointToRay(position.X,position.Y)
	end
	local mouseInstance = game.Workspace:Raycast(mouseRay.Origin,mouseRay.Direction*module.mouseDistance,module.mouseRaycastParameters)
	return mouseInstance,mouseRay,(dominantFinger or usingMouse)
end

function module.isMouseDown()
	return input:IsMouseButtonPressed(Enum.UserInputType.MouseButton1) or dominantFinger
end

function mouse()
	local pos = input:GetMouseLocation()
	local vec = game.Workspace.CurrentCamera:ViewportPointToRay(pos.x,pos.y,0)
	return game.Workspace.CurrentCamera.CFrame:PointToObjectSpace(vec.Origin+vec.Direction*300).Unit
end

function module.initialise()
	module.mouseRaycastParameters.FilterDescendantsInstances = {game.Workspace.Hidden,game.Workspace.Players}
	module.mouseRaycastParameters.FilterType = Enum.RaycastFilterType.Exclude
	module.mouseRaycastParameters.IgnoreWater = true
end

return module
