Hi Guys, first of all, Happy New Year !
So guys if you have played Restaurant Tycoon 2 (by @Ultraw), you would have seen a feature like there are tables but if there isn’t atleast one chair in a specific distance like say 1 studs from a table, then any customers can’t sit on that table. And if there is a chair in the given distance, it detects and says "Table of (how much chairs are their) created. How to achieve this as I’m heavily inspired by this game and Ultraw to create an unique game and it would be helpful for my programming knowledge. I’m assuming to use Region3. Thanks !
There are a few ways to do this actually. For tycoon games (or when it is known when the presence for nearby parts should be detected) you should probably use Region3.
For tower-defence games where you want to detect when something enters the range and exits the range, creating a part and using .Touched
and .TouchEnded
is preferable.
Ok, so my assumption of Region3 was probably right, thanks for the answer !
There’s also GetPartsInPart, GetPartBoundsInBox and GetPartBoundsInRadius, and you could use a data structure that allows you to check what placed items are in what locations.
Use magnitude like this.
While true do
Wait()
local distance = (workspace.Part1.Position -workspace.Part2.Position).Magnitude
If b < 15 then --- check if its close
print("close")
end
end)
This will essentially be the same as doing :GetPartsBoundInRadius()
. Having a while wait()
loop isn’t great as it will use a lot of CPU even if nothing is changing, the code also requires knowledge of what part2
is, which isn’t always known.
Also, you should be using task.wait()
instead of wait()
, it is more or less the new and improved version of it.
You dont necessarily need to loop this. You can simply wait to see if the parts position property has been changed and then check the distance.
Its up to you if you use task.wait(). I understand it is better however im just giving examples.
The answer is simple. You will need to use a loop to find the nearest part to your table. If you want to be able to use this on multiple tables, you will need to do this in a loop as well.
Here is the code you need to write.
Create your variable called tableOfX
and make it equal to 0
Create a loop that will loop through every part in the workspace.
In this loop, check if the part is a chair. If it is, then go to step 5.
Check in a loop if the part is within the distance of the table. If yes, go to step 5.
Add 1 to tableOfX.
After the loop finishes, print out tableOfX
. This is the amount of chairs that are near the table.
This is the code for step 4.
if (table.Position - chair.Position).Magnitude < 1 then
return true
else
return false
end