NPCs Spawning in Ground

Hello there!

I’ve you’ve ever played Gmod, you know you can install addons. I’m trying to recreate the Background NPCs addon inside Roblox.

So far, it’s great! I’m just optimizing it and such, but there’s one issue. I’m using this code to spawn NPCs in a circle.

-- Generate a random angle in radians
local angle = math.rad(math.random(0, 360))

-- Calculate the x and z coordinates on the circumference of the circle
local x = center.X + radius * math.cos(angle)
local z = center.Z + radius * math.sin(angle)

-- Create the Vector3 using the calculated coordinates
newPosition =, center.Y, z))

(center is a player’s root position)

This works great, but sometimes npcs spawn inside a wall for example. I was thinking of using raycasting to prevent this, but it sounds really slow.

Any ideas?

You could try using Region3 to check for potential collisions.

local function isPositionObstructed(position)
    -- Perform collision check
    local region = -, 2, 1), position +, 2, 1))
    local parts = workspace:FindPartsInRegion3(region, nil, math.huge)

    -- Check if any part is obstructing the position
    for _, part in ipairs(parts) do
        if part.CanCollide then
            return true

    return false

Thanks, I’ll try your code out now!

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