I am trying to create a script for my NPC scripts that will spawn them randomly around a certain area. So my script gets a random position in that area and will fire a raycast down so that it will only spawn on terrain. My current issue is that it will sometimes go inside of large parts, which makes the AI spawn inside of the part where no players can ever get to it.
My best idea at the moment would be a system where it spawns an invisible ball and drops it, then once the ball hits terrain it returns with where it hit.
(some code is hidden)
local function RandomSpawnLocation(nest) local raycastResult = workspace:Raycast(rayOrigin, rayDirection, raycastParams) if raycastResult then return raycastResult end local function spawnAI(nest) local info = CreatureInfo[functionsModule:getRandomAI(CreatureInfo)] local creature = game.ServerStorage.AI[info.Model]:Clone() -- wherever it is located task.spawn(function() local spawnLocation = RandomSpawnLocation(nest) print(spawnLocation) creature.PrimaryPart.CFrame = CFrame.new(spawnLocation.Position) end) creature.Parent = workspace.AI end