A great way to make scenes more interesting is to present them from multiple points of view. This can give a more cinematic feel to a game or might even be a plain necessity if you think of the TV-like replays found in most racing games.
After completing this recipe you will be able to add multiple cameras to the scene and switch between these predefined views.
To follow this recipe, complete the steps described in Setting up the game structure found in Chapter 1 before going on.
Let's create a new scene and look at it from different angles:
Application.py:
from direct.showbase.ShowBase import ShowBase from direct.actor.Actor import Actor from direct.interval.FunctionInterval import Func class Application(ShowBase): def __init__(self): ShowBase.__init__(self) self.pandaActor = Actor("panda", {"walk": "panda-walk"}) self.pandaActor.reparentTo(render) self.pandaActor.loop("walk") self.cameras = [self.cam, self.makeCamera(self.win)] self.cameras[1].node().getDisplayRegion(0).setActive(0) self.activeCam = 0 self.cameras[0].setPos(0, -30, 6) self.cameras[1].setPos(30, -30, 20) self.cameras[1].lookAt(0, 0, 6) self.taskMgr.doMethodLater(5, self.toggleCam, "toggle camera") def toggleCam(self, task): self.cameras[self.activeCam].node().getDisplayRegion(0).setActive(0) self.activeCam = not self.activeCam self.cameras[self.activeCam].node().getDisplayRegion(0).setActive(1) return task.again
After the necessary imports and the walking panda being added to the scene, we reach the first interesting part of this recipe, where we create a list containing the default camera and a newly added one. Additionally, we turn off the new camera with setActive(0)
, because we will use the default camera as initial point of view. We also store the index of the active camera in the activeCam
variable.
In the following lines, the positions targets of the cameras are set. Finally, we instruct the task manager to queue the call to toggleCam
and wait for five seconds until the method is called that switches back and forth between the cameras. The toggleCam
method returns task.again
, which causes it to be called again after another five seconds have passed.
In this recipe we only added one additional camera. Of course, Panda3D supports more than that and lets us create new cameras with a call to makeCamera()
. This creates a new scene node that wraps the actual camera object so we can move it around or reparent it to an object, for example. Whenever we want to toggle between cameras, we need to get the camera objects wrapped by the scene node using the node()
method. We can then turn cameras on and off by toggling the active state of the display region associated with each camera. This is done using the getDisplayRegion()
and setActive()
methods.