Skip to content

Scene, Layers and Camera

Modar Nasser edited this page Feb 26, 2023 · 9 revisions

A NasNas app or game is structured with 2 main components : Scene and Camera.

  • A Scene contains multiple Layers that holds drawables.
  • A Camera "look" at a Scene and renders on the Window what it sees.

Let's see an example to understand better how they work together (using the same class declaration as in the Get Started)

Game::Game() {
    // To be able to draw something, we need to create a Scene
    // To do this, we use the method App::createScene that takes the Scene name as argument
    auto& scene = this->createScene("my_scene");
    
    // Then, we create new Layers in the scene.
    scene.createLayers("my_layer_one", "my_layer_two");
    
    // Now, we have a scene that contains a layer, we can add a drawable to the layer
    // Multiple types of drawables can be added to a layer, including :
    // sf::Shape, sf::Text, ns::BitmapText, sf::Sprite, ns::ParticleSystem, ns::SpriteBatch, ns::ui::Widget and more
    scene.getLayer("my_layer_one").add(new sf::CircleShape(50));

    // The game scene is now set up, don't forget to create a Camera 
    // createCamera arguments are the name of the camera, its render order,
    // its view rectangle (view_size by default) and its viewport ({0, 0, 1, 1} by default) 
    // A camera with a render order of 0 will be drawn before a render order of 1 etc
    auto& camera = this->createCamera("my_camera", 0);

    // Make the camera look at the scene to render its content
    camera.lookAt(scene);
}

That's it, now if you run the program, the circle should be drawn on the window.

A few more things to know about Scene, Layer and Camera :

  • By default, a scene already has a layer you can access using Scene::getDefaultLayer, the default Layer will always be drawn before any user created Layer.
  • Layer has a utility method Layer::ySort that sort drawables by their y position. It is useful to perform Z ordering which is often used in top down games.
  • By default a drawable you add to a Layer will be managed by the Layer. If you want to manually manage a drawable, you can add it using Layer::addRaw.
  • Camera can follow any drawable using Camera::follow , you can also specify a frame delay to obtain a smooth movement using Camera::setFramesDelay , finally Camera::setLimitsRect limits camera movement to a specified rectangle.

For more informations, check the documentation for Scene, Layer and Camera.