Adding via Keyboard sensor (or any other sensor)
I suggest to replace the always sensor with a keyboard sensor.
Disable [True Level Triggering] otherwise you will get new objects as long as you hold the key.
To avoid creating objects when releasing the key you need to check the sensor status. As I do not have the code from tutorial here is a different version of it.
import bge
import random
controller = bge.logic.getCurrentController()
if all(sensor.positive for sensor in controller.sensors):
positionProvider = controller.owner
templateNames = ["Sphere", "Cube"]
templateName = random.choice(templateNames)
addedObject = positionProvider.scene.addObject(templateName, positionProvider, 100)
addedObject.setLinearVelocity(1.0, 0.0, 0.0)
Please notice I removed unnecessary code (such as main()
) and use more descriptive names by avoiding cryptic abbreviations.
Automatically find template objects
For easier configuration you can read the available template objects directly from the scene:
import bge
import random
controller = bge.logic.getCurrentController()
if all(sensor.positive for sensor in controller.sensors):
positionProvider = controller.owner
scene = positionProvider.scene
templates = scene.objectsInactive
template = random.choice(templates)
addedObject = scene.addObject(template, positionProvider, 100)
addedObject.setLinearVelocity(1.0, 0.0, 0.0)
Template objects by property
When you have several emitters you can filter templates by property. Keep in mind one object can have several properties. This means you can configure an object that it gets added by different emitters.
The emitter needs a property called "filter" as String with the name of the property to look for. The objects at the hidden layer need a property with that name (the type and value are irrelevant).
import bge
import random
controller = bge.logic.getCurrentController()
if all(sensor.positive for sensor in controller.sensors):
positionProvider = controller.owner
scene = positionProvider.scene
filterProperty = controller.owner.get("filter")
templates = [template for template in scene.objectsInactive
if filterProperty is None or
filterProperty in template]
template = random.choice(templates)
scene.addObject(template, positionProvider, 100)
Examples:
Your hidden layers contain this objects:
flame.001
property "flame"
flame.002
property "flame"
spark.001
property "flame", "spark"
smoke.001
property "smoke"
Your emitter has a property "filter" with value "flame". When you trigger the emitter it will emit one object out of flame.001
, flame.002
or spark.001
. It will never emit smoke.001
.
When you have another emitter with property "filter" set to "smoke" it will emit smoke.001
only.
When you have an emitter without property "filter" it will emit from all template objects.
When you have an emitter with property "filter" set to "fog" it will result in error as there is no matching template object at the hidden layers.