Limit Mouse Detection Range?

Decided to make a cursor for a small project that changes when hovering certain objects, but the intractability has basically an infinite range. I’ve tried to do some research on how to limit the range that the mouse detects an objects but I can’t really get a solid answer or direction. Any help is appreciated.

Here’s the code so you know what you’re working with.

local mouse = game.Players.LocalPlayer:GetMouse()
local RunService = game:GetService("RunService")
local DraggablePart = workspace:FindFirstChild("Test Object")  
local iconId = 8161207204 


RunService.RenderStepped:Connect(function() 
	if(mouse.Target == DraggablePart) then 
		mouse.Icon = "http://www.roblox.com/asset/?id=8161210039" 
	else
		mouse.Icon = "rbxassetid://"..iconId
	end
end)
1 Like

You can measure the distance from the part to character using:

https://developer.roblox.com/en-us/api-reference/function/Player/DistanceFromCharacter

Or you could use the vector formula in the article to measure the distance from the camera towards the part. Depends on what you want.

I suggest using Raycasting.
I have revamped your code using this concept.

local RunService = game:GetService("RunService")
local Players = game:GetService("Players")

local mouse = game.Players.LocalPlayer:GetMouse()
local DraggablePart = workspace:WaitForChild("Test Object")  
local iconId = 8161207204 
local camera = workspace.CurrentCamera

local player = Players.LocalPlayer
repeat task.wait() until player.Character
local character = player.Character

local maxDistance = 30

local raycastParams = RaycastParams.new()
raycastParams.FilterType = Enum.RaycastFilterType.Blacklist
raycastParams.FilterDescendantsInstances = {character}
raycastParams.IgnoreWater = true

RunService.RenderStepped:Connect(function() 
	local raycastResult = workspace:Raycast(camera.CFrame.Position, (mouse.Hit.Position - camera.CFrame.Position).Unit * maxDistance, raycastParams)	
	if raycastResult and raycastResult.Instance == DraggablePart then
		mouse.Icon = "http://www.roblox.com/asset/?id=8161210039" 
	else
		mouse.Icon = "rbxassetid://"..iconId
	end
end)

Here is are some helpful articles about Raycasting.
https://developer.roblox.com/en-us/api-reference/function/WorldRoot/Raycast

@dthecoolest’s approach also works; however, keep in mind that this approach it will only go by the position of the character. If the player is in third person, using the camera’s CFrame might be better.

Hope this helps. If you have any issues, let me know.

I really appreciate it, I’ll have to look more into raycasting in general. I’ve heard nothing but bad things coming from people trying to learn how to code, so I’m thrilled lol.

1 Like

Yeah, raycasting and CFrames can be very tricky. If you want further help, feel free to add me on Discord. My tag is jamston#1608.

1 Like