Hey guys, I was writing a slot system for my game, and I decided on using Magnitude to detect when a part is in a slot.
In my code, I have the script iterate through a folder with all the parts, and then detect when a part is nearby.
while true do
for i,v in ipairs(workspace.samples:GetChildren()) do
if (v.Position - slot1.Position).Magnitude <= 2 then
workspace.Data.roundmonsters[team]["1"].Value = v.Monster.Value
workspace.Data.roundmonsters[team]["1"].Rarity.Value = v.Rarity.Value
workspace.Data.roundmonsters[team]["1"].Strength.Value = v.Strength.Value
print("Monster selected: "..v.Monster.Value)
selected1 = true
elseif (v.Position - slot1.Position).Magnitude > 2 then
print("not in range")
workspace.Data.roundmonsters[team]["1"].Value = "none"
workspace.Data.roundmonsters[team]["1"].Rarity.Value = ""
workspace.Data.roundmonsters[team]["1"].Strength.Value = ""
selected1 = false
end
end
wait(1)
end
I did some more testing and it appears that it is waiting for every single part in the folder to be nearby, rather than the closest part. Do you have any idea how to fix this?
The problem with this is, if I break it, wouldn’t it stop the code from executing again? I want to be able to make it so that players can move the object away from it again and back.
local samples = workspace.samples:GetChildren()
local Closest -- This will be set as the closest spawn to the player
local PlayerPosition = Character.PrimaryPart.Position
while wait(0.0000000001) do
for i,v in pairs(samples:GetChildren()) do
if Closest == nil then
Closest = v
else
if (PlayerPosition - v.Position).magnitude < (Closest.Position - PlayerPosition).magnitude then
Closest = v
end
end
end
end
Use this to find the closest sample
After finding the closest you will want to see if the closest one is in range:
if (PlayerPosition - Closest.Position).magnitude <= 10 then
workspace.Data.roundmonsters[team]["1"].Value = v.Monster.Value
workspace.Data.roundmonsters[team]["1"].Rarity.Value = v.Rarity.Value
workspace.Data.roundmonsters[team]["1"].Strength.Value = v.Strength.Value
print("Monster selected: "..v.Monster.Value)
end