Spacing objects away by number value

Hello, I’ve been at this for like 3 hours now and no matter what I cannot do it so I gave in and I’m asking people for help and I do not like doing it but I have too at this point so

The problem I am having is that I’m trying to make a system where it’ll place objects around the map but if a area is already taken it will not place it there if its 50 studs away like this

If CheckIfFarEnough(Start, Last, 50) it should return true if start and last are 50 studs away from one a other.

This is what I have so far

local function CheckIfFarEnough(Start: Vector3, Last: Vector3, MinSpacing: number)
    
    local _CloseX = (Start.X - Last.X)
    local _CloseZ = (Start.Z - Last.Z)
    
    if _CloseX >= MinSpacing and _CloseZ >= MinSpacing then
        return true
    else
        return false
    end
    
end

This is where I’m stuck and I’m not even sure if my CheckIfFar is even right I am not good with math at all

for i=1, _Amount do
        table.insert(PickedAreas, __init__.GetRandomWorldArea())
    end
    
    for First, v in pairs(PickedAreas) do
        if PickedAreas[First - 1] then
            if CheckIfFarEnough(PickedAreas[First - 1], v, 50) then
                MakeDebugPart(PickedAreas[First])
            end
        end
    end
1 Like

Your first code was wrong calculated but i fixed that for you.

local function CheckIfFarEnough(Start: Vector3, Last: Vector3, MinSpacing: number): boolean
    local distance = (Start - Last).Magnitude
    return distance >= MinSpacing
end

and on the second code you Provided i added Several things.

  • i’ve added an table with vector3 areas to check if the area is blocked by an already existing area.
  • i’ve also added an MaxAttempts value to have an maximum attempts value. (if you doesnt it would count like FOREVER)
local placedSpots: {Vector3} = {}
local MAX_ATTEMPTS_PER_SPOT = 100

for i = 1, _Amount do
    local spotPlaced = false
    for attempt = 1, MAX_ATTEMPTS_PER_SPOT do
        local candidatePos = __init__.GetRandomWorldArea()

        local isClear = true
        for _, existingSpot in ipairs(placedSpots) do
            if not CheckIfFarEnough(candidatePos, existingSpot, _MinSpacing) then
                isClear = false
                break
            end
        end

        if isClear then
            table.insert(placedSpots, candidatePos)
            MakeDebugPart(candidatePos)
            spotPlaced = true
            break
        end
    end
end

I hope i could help you out with this. :v:

1 Like

Jesus dude you have no idea how hard this was for me and how long I tried to get it to work :sob:

But your fix works and it now does what I want thank you so much!

1 Like

everytime man :smiley:
im pleased that i could help you out!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.