Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do you check if a mouse target in within a certain distance?

I'm trying to make a npc's hitbox turn visible while the player is hovering over it. The problem is I want it to only become visible if the player that is hovering over it is within a certain distance.

The script is inside a tool in the StarterPack

My script:

player = game.Players.LocalPlayer
handle = script.Parent
tool = script.Parent.Parent
local ChangedPart = nil
tool.Equipped:connect(function(mouse)
    while tool:IsDescendantOf(player.Character) do -- Loops while the tool is in the player's character (equipped)
        wait(0.1)
		hovering = false
        part = mouse.target -- mouse.target is the part the mouse is pointing to....
        -- finds the part
        if part then -- checks if it found a part.
            if ChangedPart then
                ChangedPart.Transparency = 1 -- Makes last part invisible again.
                ChangedPart = nil
            end
            if part.Name == "Hitbox" and part:IsDescendantOf(workspace.NPCs) then 
            -- checks if the part is a hitbox and it is a descendant of the NPC folder.
				
        		ChangedPart = part --Stores the part it's changing....

                part.Transparency = 0 -- Changes part transparency
            else
                print("Part Not Hitbox") -- If the part isn't a npc's hitbox
            end
        else -- if didn't find a part.
       		if ChangedPart then --Tests if had a part
        		ChangedPart.Transparency = 1 --Makes last part invisible again.
        		ChangedPart = nil
       		end
            print("Not part")
        end
    end

end)

tool.Unequipped:connect(function(mouse)
    wait(.1)
    if ChangedPart then
        ChangedPart.Transparency = 1
        ChangedPart = nil
    end
end)

1 answer

✓ Accepted answer

.magnitude is used to find the distance between two parts. For example:

local player = game.Players.LocalPlayer
local char = player.Character
local torso = char.Torso
local npctorso = game.Workspace.npc.Torso
function distancebetween(part1,part2)
local magnitude = (part1.Position - part2.Position).magnitude
return magnitude
end

distancebetween(torso,npctorso)

Edit: Learn more here

This discussion is preserved as it was. New answers, comments, and votes are closed.