First of all we’re going to need to setup a Camera. A camera provides the viewport into our scene and how it is set up determines whether or not we are building a 2D or a 3D game.
Entities
In ChilliSource any game object is described as either an Entity, or a hierarchical series of Entities. An Entity is essentially a world space transform and a container for functionality. This functionality is described through Components – for example a MeshComponent or an EnemyAIComponent. Any number of Components can be attached to an Entity, resulting in a clean, modular approach to game object creation. In this case we want to create a camera, which is simply an Entity with a Camera Component attached to it.
Creating the Camera
If you open State.cpp in your project you’ll see that a camera is already provided for you. The code provided first of all takes a handle to the RenderComponentFactory from Application. This is a factory for creating all of the rendering related components such as StaticMeshComponent or SpriteComponent.
CSRendering::RenderComponentFactory* renderComponentFactory = CSCore::Application::Get()->GetSystem();
This is then used to create a PerspectiveCameraComponent. There are two types of camera component: perspective and orthographic. Typically, perspective camera components are used for 3D games, while orthographic are used for 2D. The factory method for creating a PerspectiveCameraComponent takes three parameters: the field of view (in radians), the near plane and the far plane.
CSRendering::CameraComponentSPtr cameraComponent = renderComponentFactory->CreatePerspectiveCameraComponent(CSCore::MathUtils::k_pi / 2.0f, 1.0f, 100.0f);
Next it simply creates the entity and attaches the new component.
CSCore::EntitySPtr cameraEntity = CSCore::Entity::Create();
cameraEntity->AddComponent(cameraComponent);
Creating the camera entity isn’t enough however, it still needs to be added to the Scene. The scene is a state system which contains all game objects that will be updated and rendered.
GetScene()->Add(cameraEntity);
Positioning the Camera
Now we have our camera but we still need to position and orientate it. A camera can be translated and rotated in the same way as any other Entity but there is another way which is often more convenient. An Entity’s transform provides a SetLookAt() method which is similar to gluLookAt(). The following moves the camera back 55 units, looking straight forward at [0, 0, 0]:
cameraEntity->GetTransform().SetLookAt(CSCore::Vector3(0.0f, 0.0f, -55.0f), CSCore::Vector3::k_zero, CSCore::Vector3::k_unitPositiveY);
It also sets the orientation of the camera such that Y is up. ChilliSource uses a “left-handed” coordinate system by default, so with Y-up: x+ is right, y+ is up and z+ is into the screen. It is possible to use a different coordinate system but the remaining tutorials will assume your application is left-handled and Y-up.