Write my own addObject() (2.58, Python)

Hello, I’m looking for a way to write my own addObject() function in a script file that, instead of using a pre-existing object as the 2nd parameter, it would use a set of [x, y, z] coordinates.

Would such a script be possible, or does simply adding the object require it to be “spawned” from an already existing object? Could anyone give me any tips as to how addObject works, or perhaps where I might find the code for the bge module?

You could use some form of “adder” object. This can be an empty that’s only used for adding objects. Then you can write something like:

def add_object(pos, obj):
    # This assumes you've already saved your adder object to bge.logic.adder
    bge.logic.adder.worldPosition = pos
    bge.logic.getCurrentScene().addObject(obj, bge.logic.adder)

If you want to look at the KX_Scene.addObject() code, you’ll need to grab the Blender source code and look at source/gameengine/Ketsji/KX_Scene.cpp. The addObject() method should be somewhere near the bottom.

Why not just use the current object and move it afterwards?

def add_object(pos, obj):
     owner = bge.logic.getCurrentController().owner
     added = bge.logic.getCurrentScene().addObject(obj, owner)
     added.worldPosition = pos

Thanks for the resources Moguri, I had a look at the code. I’ll have to stick with adding that empty to bge.logic for now, though it would be nice to add objects at a set of coordinates such as scene.addObject(‘object’, other.worldPosition)

The added object also gets it’s orientation and scale from the “adder” object.

Ah, that’s correct. Well, you can set the orientation and scale yourself in the function, as well.