I'm having problems spawning NPCs randomly!

hello everybody ! I have a problem, I’m using upbge (0.2.5), but I’m having problems spawning NPCs, I wanted to spawn them in specific locations and randomly, does anyone have a solution? I would be very grateful !

in this video, the author talks about generating landscapes and adding objects to the landscape randomly - you can use this to add your NPC actors if you add another block of code and change the blocks to actors but I would also check the position code so that there are no objects there, otherwise the actors will be thrown out of the level when they collide with static objects -
s = vertex.getXYZ
e = own.worldPosition + own.getAxisVect([0, 0, 1])
r = own.rayCast(e, s, 0, “”, xray=True)
h = r[0]
if not h:
#add actors to position - else pass

1 Like

A simple solution can be achieved by using empty objects that you place where you want your NPCs to spawn.
You will need to set conditions for the empty, and if these will be satisfied, the empty will add the NPC to the scene.
Assign properties to each empty which will be used to check the conditions and determine also what to add and where.

Properties assigned to empty (for example):

"NPC_spawnDist": 150 #if distance(PC,empty)>NPC_spawnDist do not add the NPC!
"NPC_name" : "enemyA" #what NPC to add?
"NPC_added" : False #If the NPC has already been added and so it is in the scene this value will be set to True
"NPC_dead" : False #if the enemy was already added and killed then this property will be set to True
"NPC_random_radius": 20 #this value can be used to compute where to add the NPC, in a radius around the empty.worldPosition

Operation of the script you are going to build (pseudo code):

if empty["NPC_dead"] == False and empty["NPC_added"] == False and getDistance(PC,empty) < empty["NPC_spawnDist"]:
   addNPC(empty["NPC_name"],generateSpawnPos(empty.worldPosition,empty["NPC_random_radius"]))
   empty["NPC_added "] = True

generateSpawnPos will be a function you will implement to generate a random vector added to empty.worldPosition in order to get the spawn position for the NPC. (maybe you want random_vector.z=0.0 so compute only x and y components)

Remember that when the NPC dies, immediately before dying he will have to set empty[“NPC_dead”] = True
And if the added NPC is far from the player you may want to remove him from the scene, then you will have to set empty["NPC_added "] = False
so that when the PC will be close enough to empty again, empty can add NPC again

This is a very simple system that you can develop writing a script that you will assign to each empty.
About performances, not necessarily you have play the script every frame, every 20/30 frames could be ok.
More complex and high-performance spawn systems can be built for large scenarios where there are a lot of spawnPoints but I think this is a good starting point.

1 Like