Skip to content

Adding Scene and Objects

sppmacd edited this page Aug 28, 2021 · 8 revisions

I assume that you have read the First Project tutorial and know the basics. In this tutorial you will learn how to define scene and add objects to it.

You will need additional header for this to work:

#include <ege/scene.h>

Creating a new Scene

The Scene is created, like other objects, with the make function:

auto scene = make<EGE::Scene>(loop);

The loop argument is very important, otherwise you will create a headless Scene (you can't render it)!

Defining an Object

The object on scene is represented by the EGE::SceneObject class. Each SceneObject has its type. To define a new SceneObject, derive from EGE::SceneObject:

class MySceneObject : public EGE::SceneObject
{
public:
    EGE_SCENEOBJECT("MySceneObject") // This is required to assign a type to SceneObject to allow saving/loading them from files

    MySceneObject(EGE::Scene& scene)
    : EGE::SceneObject(scene) {}
};

There is also possibility to create "bare" SceneObjects that are fully loaded from file. This will be covered by the next article.

SceneObjectRegistry

Information about types is stored in SceneObjectRegistry, which is created automatically by Scene or can be given as additional argument to constructor (if you have multiple Scenes with the same Objects):

auto& registry = scene->getRegistry();

New objects (derived from EGE::SceneObject) may be registered in that registry:

registry.addType<MySceneObject>();

Adding objects to scene

To add object to scene, simply call addNewObject<T>():

auto object = scene->addNewObject<MySceneObject>();

You can then manipulate the object, e.g. change its position (You need <ege/util.h> header for randomDouble)

object->setPosition({EGE::randomDouble(10, 50), EGE::randomDouble(10, 50), 0});

Don't set negative coordinates until you have a camera, otherwise you won't see anything!

If you want to assign common properties to object, simply override onInit() method:

virtual void onInit() override
{
    setPosition({EGE::randomDouble(10, 50), EGE::randomDouble(10, 50), 0});
}

You can also do this in constructor, but it will be overridden when loading objects from file in future!

You can add more SceneObjects, all with the randomized position:

for(size_t s = 0; s < 10; s++)
    scene->addNewObject<MySceneObject>();

Displaying a Scene

To display a Scene, you need a EGE::SceneWidget:

guiScreen->addNewWidget<EGE::SceneWidget>(scene);

You won't see anything because no appearance was defined for object, you can enable debug overlay to check if it works. Add the following code at the beginning of main() function:

EGE::GlobalConfig::set(EGE::GlobalConfig::Option::SceneObject_Overlay);

You should see something like this:

result

Conclusion

After this chapter you should know how to create basic objects in EGE. In the next article you will learn how to define appearance of objects.