This recipe will show you how to implement an effect that makes the scene look like it was lit from a small flashlight. This really nice effect can help you make your dark and creepy games even darker and creepier!
Follow the steps from Setting up the game structure in Chapter 1 and add a directory called textures
to the project.
Additionally, you will need a texture that represents the light point created by the flashlight, like the one shown as follows:
Let's get to the code behind this interesting effect:
textures
directory and rename it to flashlight.png
. Application.py
and add the following code:from direct.showbase.ShowBase import ShowBase from panda3d.core import * class Application(ShowBase): def __init__(self): ShowBase.__init__(self) self.world = loader.loadModel("environment") self.world.reparentTo(render) self.world.setScale(0.5) self.world.setPos(-8, 80, 0) self.proj = render.attachNewNode(LensNode("proj")) lens = PerspectiveLens() self.proj.node().setLens(lens) self.proj.reparentTo(self.cam) self.proj.setHpr(0, -5, 0) self.proj.setPos(0, 10, 0) tex = loader.loadTexture("flashlight.png") tex.setWrapU(Texture.WMClamp) tex.setWrapV(Texture.WMClamp) ts = TextureStage('ts') self.world.projectTexture(ts, tex, self.proj) self.cam.setPos(0, -10, 10)
After loading the environment
model into our scene, we add a new LensNode
, that will be used to project our flashlight texture onto the scene. We also need to assign a new PerspectiveLens
to this scene node, which defines the frustum used for projecting the texture so that the light blob appears as a small dot on near objects and becomes bigger if we point at objects that are further away. Additionally, we reparent the projector lens to the camera, move it a bit in front of it, and let it point down slightly.
Then we load the flashlight texture and set its wrap mode to WMClamp
. This means that instead of repeating the whole texture image, only the outermost pixel color is repeated. In our case this means that we have only one light blob and everything else appears black.
To conclude our effect implementation, we use the projectTexture()
method to put the flashlight texture image onto our environment
model.