Rendering images to the 2D layer

In this easy-and-short recipe you will learn how to display images in the 2D layer of Panda3D. For example, if you want to build 2D games or display a HUD in a shooter, this recipe is the way to go!

Getting ready

Apart from using the project structure found in Setting up the game structure found in Chapter 1, Setting Up Panda3D and Configuring Development Tools, you will need two texture images that will be displayed. Also, add an additional directory called textures to the project folder structure.

Note

Putting the image files into the textures directory is optional (you could also put them into the source directory) but will help you to keep your code and resources organized. You may also use a different image file format for your textures. Panda3D also supports JPEG and DDS, for example.

How to do it...

Follow these steps to put some images into the 2D rendering layer:

  1. Copy your texture image files to the textures directory and call them panda.png and test.png.
  2. Add the following code to Application.py:
    from direct.showbase.ShowBase import ShowBase
    from direct.gui.OnscreenImage import OnscreenImage
    from direct.actor.Actor import Actor
    from panda3d.core import *
    import random
    class Application(ShowBase):
    def __init__(self):
    ShowBase.__init__(self)
    self.panda = Actor("panda", {"walk": "panda-walk"})
    self.panda.reparentTo(render)
    self.panda.loop("walk")
    self.cam.setPos(0, -30, 5)
    files = ["panda.png", "test.png"]
    for i in range(30):
    OnscreenImage(random.sample(files, 1)[0],
    scale = Vec3(0.15, 0, 0.15),
    pos = Vec3(random.uniform(-1, 1), 0, random.uniform(-1, 1)),
    hpr = Vec3(0, 0, random.uniform(0, 360)))
    
  3. Press F6 to start the application:
How to do it...

How it works...

All it takes to display an image in the render2d layer of Panda3D is a call to OnscreenImage(). This loads the texture, puts it on a quad and adds it to the render2d scene graph, which is rendered using orthogonal projection after 3D drawing is done. The function also returns the created node, so we can change its properties later on.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset