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

How do I make it so an action can only happen if I am in a specific radius?

I am trying to make a fishing simulator and let the code comments speak for themselves:

local debounce = false

local whoClicked = script.Parent.Parent.Parent

local starterRod = whoClicked.Backpack.Rod

starterRod.Activated:Connect(function()

	if debounce == false then

		--I need an if distance from the part is <30 then

		debounce = true

		local Rope = Instance.new("RopeConstraint", workspace)

		Rope.Attachment0 = starterRod.Handle.Attachment0

		Rope.Attachment1 = game.Workspace.Rope2.Attachment1

		Rope.Visible = true 

		Rope.Length = 30

		starterRod.Unequipped:Connect(function()

			Rope:Destroy()

			debounce = false

		end)

		wait(10)

		Rope:Destroy()

		wait(2)

		debounce = false

	end

	--end (end the if)

end)

1 answer

✓ Accepted answer

You can use the magnitude property like so:

local part1 = -- some part
local part2 = -- some other part
local radius = 30 -- In studs

-- Get the positions
local part1Pos = part1.Position
local part2Pos = part2.Position

-- Calculate the distance between the parts using the magnitude property of Vector3's
local distance = (part2Pos - part1Pos).Magnitude

-- Check if the distance is within the radius
if distance <= radius then
	-- Code goes here
end

Tip: Use HumanoidRootPart inside of the character to represent the position as it's not affected by animations.

Here is the API reference for Vector3's, you can do more cool stuff with them:

https://developer.roblox.com/en-us/api-reference/datatype/Vector3

2 comments

1

Tysm man! it really helped a ton

0

Np, glad I could help!

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