I’m currently using a custom mouse handler in my game due to how the existing mouse is limited. It’s purpose is to mainly add new features to make a system similar to the existing mouse, but with room for adding things that are needed in my game. The only issue is at long distances from the player, the position my mouse script returns is offset.
Here’s the code for my mouse module:
Code
local UserInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")
local camera = workspace.CurrentCamera
local lengthCap = 500
local Mouse = {
Hit = CFrame.new(),
HitNormal = Vector3.new(),
Target = nil,
TargetFilter = {}
}
local function FindFilteredPartOnRay(ray)
local ignoredParts = {}
local foundPart
local foundPosition
local hitNormal
for index, filtered in pairs(Mouse.TargetFilter) do
if filtered then
table.insert(ignoredParts, filtered)
else
table.remove(Mouse.TargetFilter, index)
end
end
while not foundPart do
local currentPart, currentPosition, currentNormal = workspace:FindPartOnRayWithIgnoreList(ray, ignoredParts)
if currentPart then
if currentPart.Transparency ~= 1 then
foundPart = currentPart
foundPosition = currentPosition
hitNormal = currentNormal
else
table.insert(ignoredParts, currentPart)
end
else
break
end
end
return foundPart, foundPosition, hitNormal
end
function Mouse:GetPosition()
return UserInputService:GetMouseLocation()
end
function Mouse:BindToMouseMovement(func)
UserInputService.InputChanged:Connect(function(input)
if input.UserInputType == Enum.UserInputType.MouseMovement then
func()
end
end)
end
RunService:BindToRenderStep("MouseUpdate", 1, function()
local position = Mouse:GetPosition()
local unitRay = camera:ViewportPointToRay(position.X, position.Y + 36)
local ray = Ray.new(unitRay.Origin, unitRay.Direction * lengthCap) --TODO: Transfer to https://developer.roblox.com/en-us/api-reference/function/WorldRoot/Raycast
local hitPart, hitPosition, hitNormal = FindFilteredPartOnRay(ray)
if hitPart then
Mouse.Target = hitPart
end
if hitPosition then
Mouse.Hit = CFrame.new(hitPosition)
end
if hitNormal then
Mouse.HitNormal = hitNormal
end
end)
return Mouse
Notice how the primary part of the object is very close to the mouse when it is near the player/camera:
When the object is far from the player/camera, the center of the mouse is nowhere near the primary part of the object: