Create random objects with python

Hi people,

I think that question is very simple, but I could not find the answer anywhere.

I need to duplicate an object and add them randomly in the scene. Then only method I got is addObject, but it didn’t duplicate. How can I do that?

Thanks a lot!

Object you want to add by addObject must be in inactive layer.

Please see attached

You could also use an Edit Object actuator

Attachments

add_object.blend (486 KB)

To get randomness, you can use the random actuator to generate a random number (in a property).
Dependent on that value you can activate different EditObject/AddObjectActuators.

As well as with random.randint(minNum, maxNum), which fits into python’s flow a lot better than if you were to just use a Random actuator.

Indeed, if you use Python, the random module is the way to go. If you use Logic bricks the random actuator is the better choice ;).


import bge
from random import randint

cont = bge.logic.getCurrentController()
scene = bge.logic.getCurrentScene()
own = cont.owner

#put the object from inactive layer into a variable
object = scene.objectsInactive['object']

#generate some coordinates and place objects

for i in range(10): #adds ten random objects
     x, y, z = randint(1, 10), randint(1, 10) , 0 # change the range of random number depending on area size
     own.position = [x, y, z]
     scene.addObject(object, own) 


add the above script to an empty and leave it in your main scene. attach an always sensor but with no triggering so it just pulses the once. put your object in another layer.

in the script above ‘own’ in the addObject line refers to the position of thge empty - hence ‘own’ because the script is refering to the empty object it’s attached to.

z is set to zero because most games have a floor and you probably dont want your object being under it. However you may want to change that for truly 3d games such as space/flight sims etc.

If your scene starts at the centre and therefore your scene expands into both positive and negative axis eg between y-10 and y10 etc, then instead of ’ from random import randint’ change the randint to ‘uniform’ and replace randint elsewhere in the code with uniform. This is because random.randint doesn’t work with negative numbers - uniform does however.