A camera in Defold is a component that changes the viewport and projection of the game world. Out of the box, Defold ships with a built in render script that renders the game with no need of a camera component but you can easily replace the built in script with one that renders the game to your liking.
The camera component defines a bare bones perspective camera that provides a view and projection matrix to the render script. If you need advanced features like chasing, zooming, shake etc you will need to implement it. There are a few library camera solutions that implements common camera features. They are available from the Defold community assets portal:
To create a camera, right click a game object and select Add Component ▸ Camera. You can alternatively create a component file in your project hierarchy and add the component file to the game object.
The camera component has the following properties that defines the camera frustum:
To activate a camera and have it feed its view and projection matrices to the render script, you send the component an acquire_camera_focus message:
Each frame, the camera component that currently has camera focus will send a
"set_view_projection" message to the “@render” socket, i.e. it will arrive to your render script:
-- example.render_script -- function update(self) ... render.set_view(self.view) render.set_projection(self.projection) ... end function on_message(self, message_id, message) if message_id == hash("set_view_projection") then self.view = message.view self.projection = message.projection end end
The camera component currently supplies the render script with a perspective projection. This is well suited for 3D games. For 2D games, it is often desirable to render the scene with orthographic projection. This means that the view of the camera is no longer dictated by a frustum, but by a box. Orthographic projection is unrealistic in that it does not alter the size of objects based on their distance. An object 1000 units away will render at the same size as an object right in front of the camera.
To use orthographic projection you can ignore the projection matrix sent by the camera component and instead provide one yourself in the render script, just like the default renderscript does:
-- example_orthographic.render_script -- function update(self) ... render.set_view(self.view) local w = render.get_width() / 2 local h = render.get_height() / 2 local ortho = vmath.matrix4_orthographic(-w, w, -h, h, -1, 1) render.set_projection(ortho) ... end function on_message(self, message_id, message) if message_id == hash("set_view_projection") then self.view = message.view end end