Check players distance from part when clicking with tool

I want to check the players distance from a part when clicking on the part with a tool.

local player = game.Players.LocalPlayer
local mouse = player:GetMouse()

local tool = script.Parent

tool.Activated:Connect(function()
	local target = mouse.Target
	
	if target.Name == "Grass" then
		local tweenService = game:GetService("TweenService")
		local tweenInfo = TweenInfo.new(0.9, Enum.EasingStyle.Linear, Enum.EasingDirection.Out)
		local tween = tweenService:Create(target, tweenInfo, {Transparency = 1})
		tween:Play()
		wait(1)
		target:Destroy()
		script.Sound:Play()
	end
end)

local anim2 = Instance.new("Animation")
anim2.AnimationId = "https://www.roblox.com/Asset?=ID=18760050082"

tool.Activated:Connect(function()
	local target = mouse.Target
	
	if target.Name == "Grass" then
		local track2 = script.Parent.Parent.Humanoid:LoadAnimation(anim2)
		track2.Priority = Enum.AnimationPriority.Action
		track2:Play()
	end
end)

The script above is a LocalScript located inside of the tool. The “Grass” part is located inside of a folder in the workspace.

Im not sure how I would go about this, I havent really worked with tools much.

1 Like

Subtract the two Vector3 positions of you and the part and get it’s Magnitude.

local target = mouse.Target

if target ~= nil then
	local distance = (target.Position - script.Parent.Parent.PrimaryPart.Position).Magnitude
	
	if distance <= 10 then
		if target.Name == "Grass" then
			local track2 = script.Parent.Parent.Humanoid:LoadAnimation(anim2)
			track2.Priority = Enum.AnimationPriority.Action
			track2:Play()
		end
	end
end
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.