Ogre Tutorial 3: Reacting to collisions

The OgreRefApp layer provides a method to notify objects when they collide with some other object. We will now see how to prepare our objects to get notifications and how to react to them.

For this, we will have to:

  • Create a GameWorld class that extends OgreRefApp::World to allow adding custom objects
GameWorld.h
#include "OgreRefAppWorld.h"
 
 
class GameWorld: public OgreRefApp::World
{
public:
 
	GameWorld(SceneManager* sceneMgr, WorldType worldType = WT_REFAPP_GENERIC):
		World(sceneMgr, worldType){};
 
	ObjectMap GetObjects()
	{
		return mObjects;
	}
};
  • In the GameApplication class, overrride OgreRefAPP::createWorld to create a GameWorld instead of an OgreRefApp::World (don't forget to include “GameWorld.h”)
#include "GameWorld.h"
//...
	void createWorld()
	{
        mWorld = new GameWorld(mSceneMgr);
	}
  • Create a GameBall class to extend OgreRefApp::Ball to override the _notifyColided method
GameBall.h
#include "OgreRefAppBall.h"
#include "SoundManager.h"
 
class GameBall: public OgreRefApp::Ball
{
	unsigned int soundId;
 
public:
 
	GameBall(const String& name, Real radius):
		Ball(name,radius) {};
 
	~GameBall(){};
 
	void setupSound(unsigned int sId)
	{
		soundId=sId;
	}
 
	// Notify collided is called when two objects collide. 
	// See declaration of classes for more info on their structure
    void _notifyCollided(ApplicationObject *otherObj, const CollisionInfo& info)
	{
			SoundManager::getSingletonPtr()->playAudio( soundId, false );
	}
};
  • In the GameApplication class, replace createBall by the creation of a GameBall (don't forget to include “GameBall.h”)
#include "GameBall.h"
//...
                // This line is replaced by the code bellow
                //ball = mWorld->createBall("ball", 7, vp.position + Vector3(0,0,80));
 
                // create GameBall with radius 7
		ball = new GameBall("ball", 7);
 
                // Place it
		ball->setPosition(vp.position + Vector3(0,0,80));
 
                // Add it to the world (so that it will be used in dynamics)
		((GameWorld*) mWorld)->GetObjects()["ball"]=ball;
 
                // setup the sound associated with the ball
		unsigned int audioId;
 
		soundMgr->loadAudio( "Explosion.wav", &audioId, false);
		((GameBall*) ball)->setupSound(audioId);

Conclusion

You are now able to program different behaviors (including playing sounds) when two objects of a given type collide, such as a bullet hitting a character, a ball entering a goal, etc.