Help with magnitude

Hello,
So I’m trying to make a game similar to banana eats / survive the killer, and I have a problem. I want to make it so that players cant place traps right next to each other or on top of each other, so I came up with this:

for _, OtherTrap in pairs(CurrentMap.MapTraps:GetChildren()) do
	local Distance = (OtherTrap.Open.Position - Player.Character.HumanoidRootPart.Position).Magnitude
end

How can I detect if there are traps within a certain range?

You have the distance literally there.
You don’t need anything else.
Distance < 10 (min)

example

if Distance <= 10 then -- player is 10 studs close
end
1 Like

Tried doing this, but I can’t place a trap at-all:

				for _, OtherTrap in pairs(CurrentMap.MapTraps:GetChildren()) do
					Distance = (OtherTrap.Open.Position - Player.Character.HumanoidRootPart.Position).Magnitude
				end
				if Distance <= 10 then
					print('placing cv')
					Player.TrapDebounce.Value = true
					ClonedTrap:SetPrimaryPartCFrame(Player.Character.HumanoidRootPart.CFrame - Vector3.new(0,4.2,0))
					wait(5)
					Player.TrapDebounce.Value = false
				end

Perhaps you should move all your code into the for loop, because what’s happening now is that the if statement is currently only comparing the distance to the last trap in the MapTraps object. This is because the Distance variable is being changed each time, and the program is only moving forward when the variable has been set to the final object.

Hope this helps,
-Tom :slight_smile:

I only want it to place the trap once though, otherwise it will place the trap lots of times!

No, you can check the shortest of all the distances and then compare it. Otherwise you’re only comparing the distance to the final object in the table your for loop is comparing.

local shortestDistance = (2 ^ 32)    -- a very large number to kickstart finding the closest trap
for _, OtherTrap in pairs (CurrentMap.MapTraps:GetChildren()) do
    local newDistance = (OtherTrap.Open.Position - Player.Character.HumanoidRootPart.Position).magnitude
    if newDistance < shortestDistance then
         shortestDisance = newDistance    -- algorithm to find the closest trap
    end
end

if shortestDistance <= 10 then
    -- place trap as the closest one is more than 10 studs away
end

Hope this helps,
-Tom :slight_smile: