I am trying to make some npc zombies spawn randomly around the map (because if i spawn them all in one place it may lag)
If i math.random the vector3 values all around the map they may spawn in the building and thats not good
If I start taking each vector3 value for each spawn i want it would take forever to script video below
And so, how can I make efficient randomized spawn which will not make zombies spawn in unwanted places?
Assuming you have a rectangular map, you can have 2 parts in the 2 corners of the map as follows:
Then make a math.random
between these 2 part’s vectors and it will spawn completely randomly.
Here is a simple design:
Well, i think you can do as you did (randomly in the map), but also check if is there something in this position. It can be easily archived by creating invisible part in this position and do GetTouchingParts
to know if there any parts in this position. If none then spawn npc there.
I made a zombie game once, where they would randomly spawn on the map as well. The code that I wrote worked like this:
- Find random X and Z coordinates on the area you want to spawn them in
- Raycast from above to the ground to find the Y coordinate of the intersection
- Increment the Y coordinate with zombie:GetExtentsSize().y / 2
- zombie:MoveTo(position)
- zombie.Parent = workspace
This method still works if you build some cars and hills on the spawn area, due to the raycasting. One limitation of this algorithm is that it does cause your zombies to spawn on top of things.
If you want to include the roads, do this.
road = …Pick a random road
roadX = road.Position.X - road.Size.X/2
roadY = road.Position.Y + 2
roadZ = road.Position.Z - road.Size.Z/2
newVector = Vector3.new(math.Random(roadX, roadX + road.Size.X), roadY, math.random(roadZ, roadZ + road.Size.Z))
Then make zombie spawn at newVector.
This takes the lowest X and Z point of the road and makes the coordinate a random number between the lowest X or Z and the highest X or Z.
I added + 2 for roadY as an offset so that the zombie does not spawn inside the road.