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

How does one check if a tool clicked on a specific part?

Asked by 4 years ago

I'm trying to get a tool, that when it is equipped it can click on a CoalRock and make it disappear. But I don't know how to check if it clicked on the CoalRock or anything.

0
Click or touch? karlo_tr10 1233 — 4y

1 answer

Log in to vote
0
Answered by
karlo_tr10 1233 Moderation Voter
4 years ago

FIrst add RemoteEvent inside ReplicatedStorage and name it "Ore" after that add Localscript inside the tool:

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Ore = ReplicatedStorage:WaitForChild("Ore")
local Player = game.Players.LocalPlayer
local Mouse = Player:GetMouse() -- We need to get mouse (only in local script)
local Tool = script.Parent

Tool.Activated:Connect(function() -- Runs function when you click while holding the tool
    local Target = Mouse.Target -- Gets part that mouse is aiming at
    if Target then -- check if it exists
        if Target.Name == "CoalRock" then -- checks the name
            local Distance = (Player.Character.HumanoidRootPart.Position-Target.Position).Magnitude 
            if Distance < 15 then -- Checks if plyer is close
                Ore:FireServer(Target) -- fires to server
            end
        end
    end
end)

after that add Script in ServerScriptServic and paste this:

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Ore = ReplicatedStorage:WaitForChild("Ore")

Ore.OnServerEvent:Connect(function(Player,Target) -- Receives event from client
    local Distance = (Player.Character.HumanoidRootPart.Position-Target.Position).Magnitude
    if Distance < 15 then -- checks 2nd time if player is close cause you should always check this on server
        Target:Destroy() -- Destroys the target
    end 
end)

Note: Don't just copy and paste it, try to figure out what is happening, I made notes in the script

0
It works! But what is the main point of the second script? Does it just check the distance and then destroys the object? User#29785 0 — 4y
0
You need 2nd script cause if you destroy part with local script it would be visible to client only karlo_tr10 1233 — 4y
0
Helped me too a lot.Thanks a lot I've been trying to figure this out for a long time. SitaruDaniel 44 — 3y
Ad

Answer this question