Randomly spawned enemy location

How would I go about randomly spawning enemy’s (such as zombies) in random locations but always make it so they spawn on the ground with a not flat map. I understand how to get them to spawn along the X and Z axis but I don’t understand how I would adjust their Y position based on the terrain at the location that they spawn at. I could just have them all spawn slightly higher than the map then fall down but that looks bad and unpolished. Any feedback is appreciated!

1 Like

The way I usually do it is by having a transparent anchored part and cframing the NPCs somewhere randomly within said part.

This code is ripped straight out of one of my games

random = Random.new()

script.Parent.Parent = game.ServerScriptService

r = function(min,max,r)
	r = r or Random.new()
	max = max + 1
	return math.floor(r:NextNumber(min,max))
end

spawnAreaBlock = script.Parent

wait()

function getRandomCF()
	return spawnAreaBlock.CFrame
	*CFrame.new(r(-spawnAreaBlock.Size.x/2,spawnAreaBlock.Size.x/2),
				spawnAreaBlock.Size.y/2,
			r(-spawnAreaBlock.Size.z/2,spawnAreaBlock.Size.z/2))
	*CFrame.Angles(0,math.rad(r(-360,360)),0)
end


function spawnNewVillager()
		local newBody = _G.Z.newBodyVillager(math.random(0,9999999))
		newBody:SetPrimaryPartCFrame(getRandomCF())
		local ai = game.ServerScriptService.AiScripts.Villager:Clone()
		ai.Parent = newBody
		newBody.Parent = workspace.Bodies
		ai.Village.Value = workspace.PrimisTown
		ai.Disabled = false
		newBody:WaitForChild('Humanoid').Died:connect(function()
			wait(5)
			spawnNewVillager()
		end)
end


for i=1,script.villagerAmount.Value do
	spawn(spawnNewVillager)
end

EDIT: made words more concise with code

6 Likes

You could use Raycasting. Set the origin of the ray to an area high up at the chosen X, Z point you want them to spawn, and then point it downwards.
This should return the highest possible point they can spawn.
Example:

local positionX = math.random(-1000,1000)
local positionZ = math.random(-1000,1000)
local ray = Ray.new(Vector3.new(positionX,1000,positionZ),Vector3.new(0,-1000,0))
local _,position = workspace:FindPartOnRay(ray)
spawnEnemy(position)
8 Likes