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

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

Asked by 2 years ago

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

Log in to vote
0
Answered by
Mineloxer 187
2 years ago

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

1
Tysm man! it really helped a ton Anderssc 22 — 2y
0
Np, glad I could help! Mineloxer 187 — 2y
Ad

Answer this question