Lesson 12

Cameras and Viewports

Download the week 12 project

A camera defines the "point of view", or perspective, from which the game world is rendered. In a 2D game, a camera is optional. If no camera is defined, a default viewport will be used. You can even add multiple cameras to a scene, though only one can be "current" for any given viewport (more on that bellow).

Camera2D inherits from Node2D, meaning it can have a position, rotation, and can be added as a child to other nodes. This can be very useful if you want the camera to follow the player around the scene, for example, but there are many use cases where it would be better to manually move the camera around via scripting. For example, you will often want to limit the camera movement so that it doesn't reveal anything beyond the boundaries of the game. If the player falls into a pit and dies, you wouldn't want the camera to also "fall" off the world.

Cameras
Viewports

While there is a very close relationship between cameras and viewports, they are not the same thing. A viewport is the rendering surface where a camera's output is drawn. While a viewport can only have a single active, or "current", camera, you can create multiple cameras and switch which one is active.

The root of your scene is always a viewport that renders the scene tree to the window, but you can also create SubViewports that render the output of a child camera attached to them. SubViewports can be useful for many things, including:

  • Minimaps

  • Mirrors

  • Split-screen games

  • UI overlays

  • Rendering a 2D scene in a 3D game (or vice versa)

It is important to note that a SubViewport does not actually render anything to the scene by itself. Rather, it produces a render output that can be used by other nodes. There are two common ways to use the render output of a SubViewport.

The first is to use a SubViewportContainer. A SubViewportContainer is a UI Control that will automatically display the contents of an attached SubViewport child node. This is the easiest way to render a SubViewport directly to the screen. Because it is a UI Control, it can be added to any other Control, such as an HBoxLayout, and moved around or resized on the screen like any other Control.

The second is to use a ViewportTexture. This is a special type of Texture that gets its pixel data from a SubViewport rather than an image file, like a .png. A ViewportTexture can be used like any other texture on things like sprites and MeshInstance3Ds. When you create a ViewportTexture, you select a viewport for it to use as input. This can be any SubViewport in the scene, so you do not need to make the SubViewport a child of the node that uses the ViewportTexture.

Homework

No homework this week, because it's the end of the semester! Have a great summer.