Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by 5 years ago

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

Log in to vote
1
Answered by 5 years ago
Edited 5 years ago

.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

Ad

Answer this question