Displaying 2D Backgrounds         How to display a background 2D image using Rectangle2D

A frequently asked question is how to display a 2D background image in OGRE. Here is an example of how to achieve this using the Rectangle2D class. This also demonstrates e.g. how to easily scroll the background.

// Create background material
MaterialPtr material = MaterialManager::getSingleton().create("Background", "General");
material->getTechnique(0)->getPass(0)->createTextureUnitState("rockwall.tga");
material->getTechnique(0)->getPass(0)->setDepthCheckEnabled(false);
material->getTechnique(0)->getPass(0)->setDepthWriteEnabled(false);
material->getTechnique(0)->getPass(0)->setLightingEnabled(false);

// Create background rectangle covering the whole screen
Rectangle2D* rect = new Rectangle2D(true);
rect->setCorners(-1.0, 1.0, 1.0, -1.0);
rect->setMaterial("Background");

// Render the background before everything else
rect->setRenderQueueGroup(RENDER_QUEUE_BACKGROUND);

// Use infinite AAB to always stay visible
AxisAlignedBox aabInf;
aabInf.setInfinite();
rect->setBoundingBox(aabInf);

// Attach background to the scene
SceneNode* node = mSceneMgr->getRootSceneNode()->createChildSceneNode("Background");
node->attachObject(rect);

// Example of background scrolling
material->getTechnique(0)->getPass(0)->getTextureUnitState(0)->setScrollAnimation(-0.25, 0.0);

// Don't forget to delete the Rectangle2D in the destructor of your application:
delete rect;

Note: You cannot add the 2D Rectangle directly to the root scene node. It will not show up.

Here is the port to MOGRE:

// Create background material
MaterialPtr material = MaterialManager.Singleton.Create("Background", "General");
material.GetTechnique(0).GetPass(0).CreateTextureUnitState("rockwall.tga");
material.GetTechnique(0).GetPass(0).DepthCheckEnabled = false;
material.GetTechnique(0).GetPass(0).DepthWriteEnabled = false;
material.GetTechnique(0).GetPass(0).LightingEnabled = false;

// Create background rectangle covering the whole screen
Rectangle2D rect = new Rectangle2D(true);
rect.SetCorners(-1.0f, 1.0f, 1.0f, -1.0f);
rect.SetMaterial("Background");

// Render the background before everything else
rect.RenderQueueGroup = (byte)RenderQueueGroupID.RENDER_QUEUE_BACKGROUND;

// Use infinite AAB to always stay visible
AxisAlignedBox aab = new AxisAlignedBox();
aab.SetInfinite();
rect.BoundingBox = aab;

// Attach background to the scene
SceneNode node = mSmgr.RootSceneNode.CreateChildSceneNode("Background");
node.AttachObject(rect);

// Example of background scrolling
material.GetTechnique(0).GetPass(0).GetTextureUnitState(0).SetScrollAnimation(-0.25f, 0.0f);

See also


Alias: Displaying_2D_Backgrounds