1
23
Game
Programming
with OGRE
2008 Pearson Education, Inc. All rights reserved.
2
Come, Watson, come! The game is afoot.
— Sir Arthur Conan Doyle
For it’s one, two, three strikes
you’re out at the old ball game.
— Jack Norworth
The game is up.
— William Shakespeare
2008 Pearson Education, Inc. All rights reserved.
3
If you wish to avoid foreign collision,
you had better abandon the ocean.
— Henry Clay
There is strong shadow where
there is much light.
— Johann Wolfgang von Goethe
Wagner’s music is better than it sounds.
— Mark Twain
2008 Pearson Education, Inc. All rights reserved.
4
OBJECTIVES
In this chapter you will learn:
Some basics of game programming.
Where to find instructions on how to install
the Ogre 3D graphics engine to work with
your C++ programs on the Windows,
Linux and Mac platforms.
To create games using Ogre.
To perform collision detection.
To use Ogre to import and display graphics.
2008 Pearson Education, Inc. All rights reserved.
5
OBJECTIVES
To use OgreAL to integrate the OpenAL audio
library into your games.
To have Ogre accept keyboard input.
To create the simple game Pong® with Ogre
and OgreAL.
To use Ogre to regulate the speed of a game.
2008 Pearson Education, Inc. All rights reserved.
6
23.1
23.2
23.3
23.4
Introduction
Installing Ogre, OgreAL and OpenAL
Basics of Game Programming
The Game of Pong: Code Walkthrough
23.4.1 Ogre Initialization
23.4.2 Creating a Scene
23.4.3 Adding to the Scene
23.4.4 Animation and Timers
23.4.5 User Input
23.4.6 Collision Detection
23.4.7 Sound
23.4.9 Pong Drive
23.5 Wrap-Up
23.6 Ogre Internet and Web Resources
2008 Pearson Education, Inc. All rights reserved.
7
23.1 Introduction
2008 Pearson Education, Inc. All rights reserved.
8
23.2 Installing Ogre, OgreAL and
OpenAL
Ogre 1.4 (Eihort)
– SDK
– Source code
– www.ogre3d.org
OgreAL for Ogre 1.4
–
–
–
–
OpenAL
Ogg
Vorbis
www.deitel.com/books/cpphtp6
2008 Pearson Education, Inc. All rights reserved.
9
23.3 Basics of Game Programming
Graphics
– Ogre (Object-oriented Graphics Rendering Engine)
- Hides the tedious and complex graphics API code
– Windows, Linux and Mac
3D Models
– Computer representation of an object which can be
drawn on the screen
2008 Pearson Education, Inc. All rights reserved.
10
23.3 Basics of Game Programming
(Cont.)
Materials
– Determine an object’s appearance
- Colors are determined by red, green and blue light intensities
ranging from 0 to 1
- Textures are 2D images wrapped around a 3D model
Lighting
– Ambient—general lighting with no apparent source
– Diffuse—specific direction, reflects evenly off all surfaces
– Emissive—emanates from an object
– Specular—reflects relative to position and direction of the
viewer; makes objects appear shiny
2008 Pearson Education, Inc. All rights reserved.
11
Color
Red value
Green value
Blue value
Red
1.0
0.0
0.0
Green
0.0
1.0
0.0
Blue
0.0
0.0
1.0
Orange
1.0
0.784
0.0
Pink
1.0
0.686
0.686
Cyan
0.0
1.0
1.0
Magenta
Yellow
1.0
1.0
0.0
1.0
1.0
0.0
Black
0.0
0.0
0.0
White
1.0
1.0
1.0
Gray
0.5
0.5
0.5
Light gray
0.75
0.75
0.75
Dark gray
0.25
0.25
0.25
Fig. 23.1 | Red, green, and blue intensities of common
colors in Ogre.
2008 Pearson Education, Inc. All rights reserved.
12
23.3 Basics of Game Programming
(Cont.)
Collision Detection and Response
– Determine whether two objects are touching
– React appropriately
– Collision detection and physics libraries ease the process
Sound
– 3D sound models sounds coming from different directions
and distances
– Audio libraries allow you to add sound to the game
2008 Pearson Education, Inc. All rights reserved.
13
23.3 Basics of Game Programming
(Cont.)
Text
– Often used to communicate with the player
Timers
– Control game speed to create a consistent experience on
different computers
2008 Pearson Education, Inc. All rights reserved.
14
24 The Game of Pong: Code
Walkthrough
Four major game objects
– Ball
– Two paddles
– Rectangular playing field
2008 Pearson Education, Inc. All rights reserved.
15
Fig. 23.2 | Atari’s Pong coin-op went into commercial production in November of 1972,
selling a total of 38,000 machines. The game was designed entirely in TTL circuits,
using no CPU or game code software. Its “code” was implemented using simple
“gate” chips, timers and counter chips. This simple, fun and addictive game was the
cornerstone of what became the video game industry. (PONG® classic video
game courtesy of Atari Interactive, Inc. © 2007 Atari Interactive, Inc.
All rights reserved. Used with permission.)
2008 Pearson Education, Inc. All rights reserved.
16
Fig. 23.3 | Pong game objects.
2008 Pearson Education, Inc. All rights reserved.
17
23.4.1 Ogre Initialization
Ogre.h header file includes the most commonly
used headers
Root object is used to initialize Ogre
– showConfigDialog function displays the OGRE Engine
Rendering Setup dialog box
- Program should end if user cancels the dialog box
– initialise function creates the RenderWindow
RenderWindow is the window in which Ogre
renders graphics
2008 Pearson Education, Inc. All rights reserved.
18
Rendering subsystem
(OpenGL or Direct3D)
Color Depth
Resolution
Fig. 23.6 | OGRE Engine Rendering Setup dialog box.
2008 Pearson Education, Inc. All rights reserved.
1
// Pong.h
2
// Pong class definition (represents a game of Pong).
3
#ifndef PONG_H
4
#define PONG_H
5
19
Outline
Include the most common Ogre header files
6
#include <Ogre.h> // Ogre class definition
7
8
using namespace Ogre; // use the Ogre namespace
9
#include <OIS\OISEvents.h> // OISEvents class definition
Pong.h
(1 of 3)
10 #include <OIS\OISInputManager.h> // OISInputManager class definition
11 #include <OIS\OISKeyboard.h> // OISKeyboard class definition
12
13 class Ball; // forward declaration of class Ball
14 class Paddle; // forward declaration of class Paddle
15
16 enum Players { PLAYER1, PLAYER2 };
Inherit from FrameListener and
KeyListener
17
18 class Pong : public FrameListener, public OIS::KeyListener
19 {
20 public:
21
Pong(); // constructor
22
~Pong(); // destructor
23
void run(); // run a game of KeyListener
Pong
functions
24
25
// handle keyPressed and keyReleased events
26
bool keyPressed( const OIS::KeyEvent &keyEventRef );
27
bool keyReleased( const OIS::KeyEvent &keyEventRef );
28
2008 Pearson Education,
Inc. All rights reserved.
29
// move the game objects and control interactions between frames
30
virtual bool frameStarted( const FrameEvent &frameEvent );
31
virtual bool frameEnded( const FrameEvent &frameEvent );
32
static void updateScore( Players player ); // update the score
33
34 private:
FrameListener functions
35
void createScene(); // create the scene to be rendered
36
static void updateScoreText(); //Important
update the
score
on the screen
Ogre
objects
20
Outline
Pong.h
(2 of 3)
37
38
// Ogre objects
39
Root *rootPtr; // pointer to Ogre's Root object
40
SceneManager *sceneManagerPtr; // pointer to the SceneManager
41
RenderWindow *windowPtr; // pointer to RenderWindow to render scene in
42
Viewport *viewportPtr; // pointer to Viewport, area that a camera sees
43
Camera *cameraPtr; // pointer to a Camera in the scene
44
2008 Pearson Education,
Inc. All rights reserved.
45
// OIS input objects
46
OIS::InputManager *inputManagerPtr; // pointer to the InputManager
47
OIS::Keyboard *keyboardPtr; // pointer to the Keyboard
21
Outline
48
49
50
// game objects
Important
Ball *ballPtr; // pointer to the Ball
input handling objects (OIS)
51
52
Paddle *leftPaddlePtr; // pointer to player 1's Paddle
Paddle *rightPaddlePtr; // pointer to player 2's Paddle
53
54
// variables to control game states
Game
55
bool quit, pause; // did user quit or pause the game?
56
Real time; // used to delay the motion of a new Ball
57
58
static bool wait; // should the Ball's movement be delayed
59
static int player1Score; // player 1's score
60
static int player2Score; // player 2's score
Control variables
Pong.h
(3 of 3)
objects (ball and paddles)
61 }; // end class Pong
62
63 #endif // PONG_H
2008 Pearson Education,
Inc. All rights reserved.
1
// Pong.cpp
2
// Pong class member-function definitions.
3
#include <sstream>
4
using std::ostringstream;
22
Outline
5
6
#include <stdexcept>
7
8
using std::runtime_error;
9
#include <Ogre.h> // Ogre class definition
Pong.cpp
(1 of 12)
10 using namespace Ogre; // use the Ogre namespace
11
12 #include <OgreAL.h> // OgreAL class definition
13 #include <OgreStringConverter.h> // OgreStringConverter class definition
14 #include <OIS\OISEvents.h> // OISEvents class definition
15 #include <OIS\OISInputManager.h> // OISInputManager class definition
16 #include <OIS\OISKeyboard.h> // OISKeyboard class definition
17 #include "Ball.h" // Ball class definition
18 #include "Paddle.h" // Paddle class definition
19 #include "Pong.h" // Pong class definition
20
21 int Pong::player1Score = 0; // initialize player 1's score to 0
22 int Pong::player2Score = 0; // initialize player 2's score to 0
Vector3s
23 bool Pong::wait = false; // initialize wait to false
used to move the Paddles
24
25 // directions to move the Paddles
26 const Vector3 PADDLE_DOWN = Vector3( 0, -15, 0 );
27 const Vector3 PADDLE_UP = Vector3( 0, 15, 0 );
28
2008 Pearson Education,
Inc. All rights reserved.
29 // constructor
30 Pong::Pong()
23
Create the Root object
Outline
31 {
32
rootPtr = new Root(); // initialize Root object
33
34
// use the Ogre Config Dialog Box to choose the settings
35
36
if ( !( rootPtr->showConfigDialog() ) ) // user canceled the dialog box
Create
the Diaglog
RenderWindow
throw runtime_error( "User Canceled Ogre
Setup
Box." );
37
38
39
// get a pointer to the RenderWindow
windowPtr = rootPtr->initialise( true, "Pong"
); thebox
SceneManager
UseCreate
a dialog
to choose render
40
41
42
Pong.cpp
(2 of 12)
settings, end program if user cancels
Camera
// create the SceneManager
Create and ST_GENERIC
configure the
sceneManagerPtr = rootPtr->createSceneManager(
);
43
44
45
46
47
48
// create the Camera
cameraPtr = sceneManagerPtr->createCamera( "PongCamera" );
cameraPtr->setPosition( Vector3( 0, 0, 200 ) ); // set Camera position
cameraPtr->lookAt( Vector3( 0, 0, 0 ) ); // set where Camera looks
cameraPtr->setNearClipDistance( 5 ); // near distance Camera can see
49
50
cameraPtr->setFarClipDistance( 1000 ); // far distance Camera can see
51
52
// create the Viewport
viewportPtr = windowPtr->addViewport( cameraPtr );
53
54
55
viewportPtr->setBackgroundColour( ColourValue( 0, 0, 0 ) );
56
57
cameraPtr->setAspectRatio( Real( viewportPtr->getActualWidth() ) /
( viewportPtr->getActualHeight() ) );
Display the Camera’s content in the
RenderWindow
// set the Camera's aspect ratio
58
2008 Pearson Education,
Inc. All rights reserved.
59
// set the scene's ambient light
60
sceneManagerPtr->setAmbientLight( ColourValue( 0.75, 0.75, 0.75 ) );
24
61
62
// create the Light
63
Light *lightPtr = sceneManagerPtr->createLight( "Light" ); // a Light
64
lightPtr->setPosition( 0, 0, 50 ); // set the Light's position
65
66
unsigned long hWnd; // variable to hold the window handle
67
windowPtr->getCustomAttribute( "WINDOW", &hWnd ); // get window handle
68
OIS::ParamList paramList; // create
Create a Point Light
and set its position
an OIS ParamList
Outline
Pong.cpp
(3 of 12)
69
70
// add the window to the ParamList
71
paramList.insert( OIS::ParamList::value_type( "WINDOW",
72
73
Create the InputManager which
manages the various input objects
Represent the keyboard as an object
Ogre::StringConverter::toString(
hWnd ) ) );
74
// create the InputManager
75
inputManagerPtr = OIS::InputManager::createInputSystem( paramList );
76
keyboardPtr = static_cast< OIS::Keyboard* >( inputManagerPtr->
77
78
Register
object
Ogre to
createInputObject( OIS::OISKeyboard,
true this
) );Pong
// create
a with
Keyboard
keyboardPtr->setEventCallback( this ); receive
// add aFrameEvent
KeyListener
notifications
79
80
Register this Pong object with the
Keyboard to receive KeyEvent
Load the scripts, meshes and sounds
notifications
rootPtr->addFrameListener( this ); // add this Pong as a FrameListener
81
82
// load resources for Pong
83
ResourceGroupManager::getSingleton().addResourceLocation(
84
85
"../../media/PongResources", "FileSystem", "Pong" );
ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
86
2008 Pearson Education,
Inc. All rights reserved.
87
quit = pause = false; // player has not quit or paused the game
88
time = 0; // initialize the time since Ball was reset to 0
89 } // end Pong constructor
25
Outline
90
91 // Pong destructor erases objects contained in a Pong object
92 Pong::~Pong()
93 {
94
// free dynamically allocated memory for Keyboard
95
inputManagerPtr->destroyInputObject( keyboardPtr );
96
OIS::InputManager::destroyInputSystem( inputManagerPtr );
97
98
// free dynamically allocated memory for Root
99
delete rootPtr; // release memory pointer points to
100
rootPtr = 0; // point pointer at 0
Pong.cpp
(4 of 12)
Use InputManager functions
to destroy OIS objects
101
102
// free dynamically allocated memory for Ball
103
delete ballPtr; // release memory pointer points to
104
ballPtr = 0; // point pointer at 0
105
106
// free dynamically allocated memory for Paddle
107
delete leftPaddlePtr; // release memory pointer points to
108
leftPaddlePtr = 0; // point pointer at 0
109
110
// free dynamically allocated memory for Paddle
111
delete rightPaddlePtr; // release memory pointer points to
112
rightPaddlePtr = 0; // point pointer at 0
113 } // end Pong destructor
114
2008 Pearson Education,
Inc. All rights reserved.
115 // create the scene to be displayed
26
116 void Pong::createScene()
Outline
117 {
118
// get a pointer to the Score Overlay
119
Overlay *scoreOverlayPtr =
120
OverlayManager::getSingleton().getByName( "Score" );
121
122
scoreOverlayPtr->show(); // show the Overlay
123
// make the game objects
128
Use the OverlayManager to
access the Score Overlay
ballPtr->addToScene(); // add the Ball to the scene
and show
it on the screen
rightPaddlePtr = new Paddle( sceneManagerPtr,
90 );
Add "RightPaddle",
the Ball and the
Paddles
rightPaddlePtr->addToScene(); // add a Paddle to the scene
to the scene
leftPaddlePtr = new Paddle( sceneManagerPtr, "LeftPaddle", -90 );
129
leftPaddlePtr->addToScene(); // add a Paddle to the
scene
Use
the
124
125
126
127
Pong.cpp
(5 of 12)
ballPtr = new Ball( sceneManagerPtr ); // make the Ball
130
SceneManager to create an
Entity representing a wall
131
// create the walls
132
Entity *entityPtr = sceneManagerPtr->
133
134
createEntity( "WallLeft", "cube.mesh" ); // create the left wall
entityPtr->setMaterialName( "wall" ); // set material for left wall
135
entityPtr->setNormaliseNormals( true ); // fix the normals when scaled
136
Set the material used to color the wall
Recalculate lighting effects
whenever the Entity is resized
2008 Pearson Education,
Inc. All rights reserved.
137
// create the SceneNode for the left wall
138
SceneNode *nodePtr = sceneManagerPtr->getRootSceneNode()->
139
27
createChildSceneNode( "WallLeft" );
140
nodePtr->attachObject( entityPtr ); // attach leftCreate
wall to
SceneNode
a SceneNode
141
nodePtr->setPosition( -95, 0, 0 ); // set the left
142
nodePtr->setScale( .05, 1.45, .1 ); // set the left wall's size
143
144
Attach the wall
Entity to
the new );
entityPtr = sceneManagerPtr->createEntity(
"WallRight",
"cube.mesh"
entityPtr->setMaterialName( "wall"SceneNode
); // set material for right wall
145
146
147
148
149
that is a child
Retrieve
the
root
SceneNode
wall's
of theposition
root SceneNode
Set the
the
position
ofwall
the
Change
size
entityPtr->setNormaliseNormals(
true
); of
//the
fix
theSceneNode
normals when scaled
Pong.cpp
(6 of 12)
relative to its current size
// create the SceneNode for the right wall
nodePtr = sceneManagerPtr->getRootSceneNode()->
createChildSceneNode( "WallRight" );
150
nodePtr->attachObject( entityPtr ); // attach right wall to SceneNode
151
nodePtr->setPosition( 95, 0, 0 ); // set the right wall's position
152
nodePtr->setScale( .05, 1.45, .1 ); // set the right wall's size
153
entityPtr = sceneManagerPtr->createEntity( "WallBottom", "cube.mesh" );
154
entityPtr->setMaterialName( "wall" ); // set material for bottom wall
155
156
entityPtr->setNormaliseNormals( true ); // fix the normals when scaled
157
// create the SceneNode for the bottom wall
158
nodePtr = sceneManagerPtr->getRootSceneNode()->
159
Outline
createChildSceneNode( "WallBottom" );
160
nodePtr->attachObject( entityPtr ); // attach bottom wall to SceneNode
161
nodePtr->setPosition( 0, -70, 0 ); // set the bottom wall's position
162
nodePtr->setScale( 1.95, .05, .1 ); // set bottom wall's size
163
entityPtr = sceneManagerPtr->createEntity( "WallTop", "cube.mesh" );
164
entityPtr->setMaterialName( "wall" ); // set the material for top wall
165
entityPtr->setNormaliseNormals( true ); // fix the normals when scaled
166
2008 Pearson Education,
Inc. All rights reserved.
167
// create the SceneNode for the top wall
168
nodePtr = sceneManagerPtr->getRootSceneNode()->
169
createChildSceneNode( "WallTop" );
170
nodePtr->attachObject( entityPtr ); // attach top wall to the SceneNode
171
nodePtr->setPosition( 0, 70, 0 ); // set the top wall's position
172
nodePtr->setScale( 1.95, .05, .1 ); // set the top wall's size
173 } // end function createScene
174
175 // start a game of Pong
28
Outline
Pong.cpp
(7 of 12)
176 void Pong::run()
177 {
178
createScene(); // create the scene
179
rootPtr->startRendering(); // start rendering frames
180 } // end function run
181
182 // update the score
Start rendering and continue until
frameStarted or frameEnded
return false
player's score
183 void Pong::updateScore( Players player )
184 {
185
186
187
188
189
// increase the correct
if ( player == Players::PLAYER1 )
player1Score++;
else
player2Score++;
Set the control variable to pause the
Ball’s movement after a player scores
190
191
wait = true; // the game should wait to restart the Ball
192
updateScoreText(); // update the score text on the screen
193 } // end function updateScore
194
2008 Pearson Education,
Inc. All rights reserved.
195 // update the score text
29
196 void Pong::updateScoreText()
Outline
197 {
198
ostringstream scoreText; // text to be displayed
199
Use the OverlayManager to access
scoreText << "Player 2 Score: " << player2Score;
a TextAreaOverlayElement
200
201
202
// make the text
// get the right player's TextArea
Pong.cpp
(8 of 12)
203
OverlayElement *textElementPtr =
204
205
OverlayManager::getSingletonPtr()->getOverlayElement( "right" );
textElementPtr->setCaption( scoreText.str() ); // set the text
206
207
scoreText.str( "" ); // reset the text in scoreText
208
scoreText << "Player 1 Score: " << player1Score;
// make
the text
Change the text
displayed
by
209
210
// get the left player's TextArea
211
textElementPtr =
212
a
TextAreaOverlayElement
OverlayManager::getSingletonPtr()->getOverlayElement( "left" );
213
textElementPtr->setCaption( scoreText.str() ); // set the text
214 } // end function updateScoreText
215
2008 Pearson Education,
Inc. All rights reserved.
216 // respond to user keyboard input
30
217 bool Pong::keyPressed( const OIS::KeyEvent &keyEventRef )
218 {
219
// if the game is not paused
220
if ( !pause )
221
{
Get the KeyCode from the KeyEvent
222
223
// process KeyEvents that apply when the game is not paused
switch ( keyEventRef.key )
224
{
225
case OIS::KC_ESCAPE: // escape key hit: quit
226
quit = true;
227
break;
228
rightPaddlePtr->movePaddle( PADDLE_UP );
230
break;
rightPaddlePtr->movePaddle( PADDLE_DOWN );
233
break;
236
237
(9 of 12)
case OIS::KC_DOWN: //down-arrow key hit: move the right Paddle down
232
234
235
Pong.cpp
case OIS::KC_UP: // up-arrow key hit: move the right Paddle up
229
231
Outline
case OIS::KC_A: // A key hit: move the left
leftPaddlePtr->movePaddle( PADDLE_UP );
Move the Paddles based on what
Paddle key
up was pressed
break;
case OIS::KC_Z: // Z key hit: move the left Paddle down
238
leftPaddlePtr->movePaddle( PADDLE_DOWN );
239
break;
2008 Pearson Education,
Inc. All rights reserved.
case OIS::KC_P: // P key hit: pause the game
240
31
241
pause = true; // set pause to true when the user pauses the game
242
Overlay *pauseOverlayPtr =
OverlayManager::getSingleton().getByName( "PauseOverlay" );
243
244
pauseOverlayPtr->show(); // show the pause Overlay
245
break;
246
247
} // end switch
} // end if
248
else // game is paused
249
{
Pong.cpp
Show the PauseOverlay
Pause the game when the user hits P
250
// user hit 'R' on the keyboard
251
if ( keyEventRef.key == OIS::KC_R )
252
{
pause = false; // set pause to false when user resumes the game
254
Overlay *pauseOverlayPtr =
256
257
258
259
(10 of 12)
If the game is paused, only respond
to the R key
253
255
Outline
OverlayManager::getSingleton().getByName( "PauseOverlay" );
pauseOverlayPtr->hide(); // hide the pause Overlay
} // end if
} // end else
return true;
Hide the PauseOverlay
260 } // end function keyPressed
261
262 // process key released events
263 bool Pong::keyReleased( const OIS::KeyEvent &keyEventRef )
264 {
265
return true;
266 } // end function keyReleased
267
2008 Pearson Education,
Inc. All rights reserved.
268 // return true if the program should render the next frame
269 bool Pong::frameEnded( const FrameEvent &frameEvent )
270 {
271
Outline
return !quit; // quit = false if the user hasn't quit yet
272 } // end function frameEnded
273
Called at the beginning of
Calledevery
at theframe
end of every frame
274 // process game logic, return true if the next frame should be rendered
275 bool Pong::frameStarted( const FrameEvent &frameEvent )
Collect KeyEvents from the keyboard
276 {
277
keyboardPtr->capture(); // get keyboard events
278
// the game is not paused and the Ball should move
279
if ( !wait && !pause )
280
{
Pong.cpp
(11 of 12)
If the game and Ball aren’t
paused, move the Ball
281
// move the Ball
282
ballPtr->moveBall( frameEvent.timeSinceLastFrame );
283
32
} // end if
The time, in seconds, since the
last frame was rendered
2008 Pearson Education,
Inc. All rights reserved.
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
// don't move the Ball if wait is true
else if ( wait )
{
// increase time if it is less than 4 seconds
Wait to move the Ball for four
if ( time < 4 )
seconds after a player scores
// add the seconds since the last frame
time += frameEvent.timeSinceLastFrame;
else
{
33
Outline
Pong.cpp
(12 of 12)
wait = false; // shouldn't wait to move the Ball any more
time = 0; // reset the control variable to 0
} // end else
} // end else
return !quit; // quit = false if the user hasn't quit yet
299 } // end function frameStarted
2008 Pearson Education,
Inc. All rights reserved.
1
// Ball.h
2
// Ball class definition (represents a bouncing ball).
3
#ifndef BALL_H
4
#define BALL_H
34
Outline
5
6
#include <Ogre.h> // Ogre class definition
7
8
using namespace Ogre; // use the Ogre namespace
9
#include <OgreAL.h> // OgreAL class definition
Ball.h
(1 of 2)
10
11 class Paddle; // forward declaration of class Paddle
12
13 const int RADIUS = 5; // the radius of the Ball
14
15 class Ball
Radius of the Ball
16 {
17 public:
18
Ball( SceneManager *sceneManagerPtr ); // constructor
19
20
~Ball(); // destructor
Add the
void addToScene(); // add the Ball to the scene
21
void moveBall( Real time ); // move the Ball across the screen
Ball to the scene
22
Move the Ball based on time
2008 Pearson Education,
Inc. All rights reserved.
23 private:
35
24
SceneManager *sceneManagerPtr; // pointer toOgreAL
the SceneManager
object to manage
sounds
25
SceneNode *nodePtr; // pointer to the SceneNode
26
OgreAL::SoundManager *soundManagerPtr; // pointer to the SoundManager
27
OgreAL::Sound *wallSoundPtr; // sound played when Ball hits a wall
28
OgreAL::Sound *paddleSoundPtr; // sound played when Ball hits a Paddle
29
OgreAL::Sound *scoreSoundPtr; // sound played when someone scores
30
int speed; // speed of the Ball
31
Vector3 direction; // direction of the Ball
Outline
Ball.h
(2 of 2)
Sound effects used in the game
32
33
// private utility functions
34
void reverseHorizontalDirection(); // change horizontal direction
35
void reverseVerticalDirection(); // change vertical direction
36
void hitPaddle(); // control the Ball hitting the Paddles
37 }; // end class Ball
Change the direction of the Ball
38
39 #endif // BALL_H
2008 Pearson Education,
Inc. All rights reserved.
1
// Ball.cpp
2
// Ball class member-function definitions.
3
#include <Ogre.h> // Ogre class definition
4
using namespace Ogre; // use the Ogre namespace
36
Outline
5
6
#include <OgreAL.h> // OgreAL class definition
7
8
#include "Ball.h" // Ball class definition
#include "Paddle.h" // Paddle class definition
9
#include "Pong.h" // Pong class definition
Ball.cpp
(1 of 7)
10
11 // Ball constructor
12 Ball::Ball( SceneManager *ptr )
13 {
Create the SoundManager
14
sceneManagerPtr = ptr; // set pointer to the SceneManager
15
soundManagerPtr = new OgreAL::SoundManager(); // create SoundManager
16
speed = 100; // speed of the Ball
17
direction = Vector3( 1, -1, 0 ); // direction of the Ball
18 } // end Ball constructor
19
20 // Ball destructor
21 Ball::~Ball()
22 {
23
Direction is determined by a
Vector3
// empty body
24 } // end Ball destructor
25
2008 Pearson Education,
Inc. All rights reserved.
26 // add the Ball to the scene
37
27 void Ball::addToScene()
Outline
28 {
29
// create Entity and attach it to a node in the scene
30
Entity *entityPtr =
31
sceneManagerPtr->createEntity( "Ball", "sphere.mesh" );
32
33
entityPtr->setMaterialName( "ball" ); // set material for the Ball
entityPtr->setNormaliseNormals( true ); // fix the normals when scaled
34
nodePtr = sceneManagerPtr->getRootSceneNode()->
35
createChildSceneNode( "Ball" ); // create a SceneNode
nodePtr->attachObject( entityPtr ); // attach the Entity to SceneNode
37
nodePtr->setScale( .05, .05, .05 ); // scale SceneNode
39
a Sound
to
// attach sounds to Ball so they will Create
play from
where object
Ball is
40
wallSoundPtr = soundManagerPtr->
41
be played
createSound( "wallSound", "wallSound.wav", false );
42
nodePtr->attachObject( wallSoundPtr ); // attach a sound to SceneNode
43
paddleSoundPtr = soundManagerPtr->
44
45
createSound( "paddleSound", "paddleSound.wav", false );
Add the Sound
nodePtr->attachObject( paddleSoundPtr ); // attach sound to SceneNode
46
scoreSoundPtr = soundManagerPtr->
47
(2 of 7)
Use the sphere mesh to
represent the Ball
36
38
Ball.cpp
to the scene by
attaching it to a SceneNode
createSound( "cheer", "cheer.wav", false ); // create a Sound
48
49
// attach the score sound to its own node centered at ( 0, 0, 0 )
50
sceneManagerPtr->getRootSceneNode()->createChildSceneNode( "score" )->
51
attachObject( scoreSoundPtr );
52 } // end function addToScene
The soundDon’t
file toloop
be played
the sound
53
2008 Pearson Education,
Inc. All rights reserved.
54 // move the Ball across the screen
55 void Ball::moveBall( Real time )
56 {
57
58
retrieve a SceneNode by name
// get the positions of the four walls
Vector3 topPosition = sceneManagerPtr->
Vector3 bottomPosition = sceneManagerPtr->
getSceneNode( "WallBottom" )->getPosition();
Vector3 leftPosition = sceneManagerPtr->
Vector3 rightPosition = sceneManagerPtr->
getSceneNode( "WallRight" )->getPosition();
68
69
70
Get the position of a SceneNode
as a Vector3
getSceneNode( "WallLeft" )->getPosition();
66
67
const int WALL_WIDTH = 5; //
71
If the Ball’s left side (x-coordinate minus radius)
the width of the walls is less left wall’s right side (x-coordinate plus
half the width), it hit the wall
Put
the
Ball
in
the
middle
of the screen
left side
72
73
// check if the Ball hit the
if ( ( position.x - RADIUS ) <= leftPosition.x + ( WALL_WIDTH / 2 ) )
74
{
Give player 2 a point
75
nodePtr->setPosition( 0, 0, 0 ); // place Ball in center of screen
76
Pong::updateScore( Players::PLAYER2 ); // update the score
77
scoreSoundPtr->play(); // play a sound when player 2 scores
78
Ball.cpp
(3 of 7)
getSceneNode( "WallTop" )->getPosition();
64
65
Outline
Use the SceneManager
to new position
Vector3 position = nodePtr->getPosition();
// get Ball's
62
63
38
nodePtr->translate( ( direction * ( speed * time ) ) ); // move Ball
59
60
61
Move a SceneNode relative
to its current position
} // end if
Play the sound effect
2008 Pearson Education,
Inc. All rights reserved.
79
// check if the Ball hit the right side
80
else if (
( position.x + RADIUS ) >= rightPosition.x - ( WALL_WIDTH / 2 ) )
81
82
39
{
83
nodePtr->setPosition( 0, 0, 0 ); // place Ball in center of screen
84
Pong::updateScore( Players::PLAYER1
); Ball
// update
the score
If the bottom of the
(y-coordinate
minus radius)
85
86
scoreSoundPtr->play(); // play a sound when player 1 scores
is less than the top of the bottom wall (y-coordinate
} // end else
87
// check if the Ball hit the bottom wall
88
else if (
plus half the width) it hit the wall
89
( position.y
90
direction.y < 0 )
91
{
93
nodePtr->setPosition( position.x,
( bottomPosition.y + ( WALL_WIDTH / 2 ) + RADIUS ), position.z );
94
reverseVerticalDirection(); // make the Ball start moving up
95
96
} // end else
97
98
// check if the Ball hit the top wall
else if (
Make the Ball start moving up
99
( position.y + RADIUS ) >= topPosition.y - ( WALL_WIDTH / 2 ) &&
100
direction.y > 0 )
{
102
// place the Ball on the top wall
103
nodePtr->setPosition( position.x,
105
106
(4 of 7)
Place the Ball at the edge of the wall
// place the Ball on the bottom wall
104
Ball.cpp
- RADIUS ) <= bottomPosition.y + ( WALL_WIDTH / 2 ) &&
92
101
Outline
( topPosition.y - ( WALL_WIDTH / 2 ) - RADIUS ), position.z );
reverseVerticalDirection(); // make the Ball start moving down
} // end else
107
2008 Pearson Education,
Inc. All rights reserved.
108
hitPaddle(); // check if the Ball hit a Paddle
40
109 } // end function moveBall
Outline
110
111 // reverse the Ball's horizontal direction
112 void Ball::reverseHorizontalDirection()
Change the sign of the x
component in the vector
113 {
114
115
direction *= Vector3( -1, 1, 1 ); // reverse the horizontal direction
paddleSoundPtr->play(); // play the "paddleSound" sound effect
116 } // end function reverseHorizontalDirection
117
Ball.cpp
(5 of 7)
Play the appropriate sound effect
the sign of the y
component in the vector
118 // reverse the Ball's vertical direction
Change
119 void Ball::reverseVerticalDirection()
120 {
121
direction *= Vector3( 1, -1, 1 ); // reverse the vertical direction
122
wallSoundPtr->play(); // play the "wallSound" sound effect
123 } // end function reverseVerticalDirection
124
125 // control the Ball colliding with the Paddle
126 void Ball::hitPaddle()
127 {
Play the appropriate sound effect
128
// get the position of the Paddles and the Ball
129
Vector3 leftPaddlePosition = sceneManagerPtr->
130
131
132
133
getSceneNode( "LeftPaddle" )->getPosition(); // left Paddle
Vector3 rightPaddlePosition = sceneManagerPtr->
getSceneNode( "RightPaddle" )->getPosition(); // right
Get the positions of the
PaddleBall and Paddles
Vector3 ballPosition = nodePtr->getPosition(); // the Ball's position
134
135
const int PADDLE_WIDTH = 2; // width of the Paddle
136
const int PADDLE_HEIGHT = 30; // height of the Paddle
137
Dimensions of a Paddle
2008 Pearson Education,
Inc. All rights reserved.
138
// is the Ball in range of the left Paddle?
139
if ( ( ballPosition.x - RADIUS ) <
( leftPaddlePosition.x + ( PADDLE_WIDTH / 2 ) ) )
140
141
{
142
// check for collision with left Paddle
143
if ( ( ballPosition.y - RADIUS ) <
144
( leftPaddlePosition.y + ( PADDLE_HEIGHT / 2 ) ) &&
145
( ballPosition.y + RADIUS ) >
146
( leftPaddlePosition.y - ( PADDLE_HEIGHT / 2 ) ) )
147
148
149
150
151
41
Outline
Check if the Ball is far enough
left to hit the left Paddle
// reverse the Ball's direction
CheckreverseHorizontalDirection();
if the Ball’s y-coordinate is between
the top and bottom of the Paddle
Change the direction of the Ball
// place the Ball at the edge of the Paddle
Place the Ball at the edge of the Paddle
nodePtr->setPosition(
( leftPaddlePosition.x + ( PADDLE_WIDTH / 2 ) + RADIUS ),
153
ballPosition.y, ballPosition.z );
155
(6 of 7)
{
152
154
Ball.cpp
} // end if
} // end if
2008 Pearson Education,
Inc. All rights reserved.
156
// is the Ball in range of the right Paddle?
157
else if ( ( ballPosition.x + RADIUS ) >
( rightPaddlePosition.x - ( PADDLE_WIDTH / 2 ) ) )
158
159
160
161
Outline
{
// check for collision with right Paddle
if ( ( ballPosition.y - RADIUS ) <
162
163
( rightPaddlePosition.y + ( PADDLE_HEIGHT / 2 ) ) &&
( ballPosition.y + RADIUS ) >
164
165
( rightPaddlePosition.y - ( PADDLE_HEIGHT / 2 ) ) )
166
42
Ball.cpp
(7 of 7)
{
reverseHorizontalDirection(); // reverse the Ball's direction
167
168
169
// place the Ball at the edge of the Paddle
nodePtr->setPosition(
170
( rightPaddlePosition.x - ( PADDLE_WIDTH / 2 ) - RADIUS ),
171
ballPosition.y, ballPosition.z );
172
} // end if
173
} // end else
174 } // end function hitPaddle
2008 Pearson Education,
Inc. All rights reserved.
1
// ball material definition
2
material ball
3
{
43
Name of the material
4
// define one technique for rendering the Ball
5
technique
6
{
7
8
// render the Ball in one pass
pass
9
{
10
// color the Ball violet
11
ambient 0.58 0 0.827
12
diffuse 0.58 0 0.827
13
specular 0.58 0 0.827 120
16 }
What color light the object reflects
}
14
15
Outline
}
How shiny the object is (any
value greater than 0)
2008 Pearson Education,
Inc. All rights reserved.
1
// Paddle.h
2
// Paddle class definition (represents a paddle in the game).
3
#ifndef PADDLE_H
4
#define PADDLE_H
44
Outline
5
6
#include <Ogre.h> // Ogre class definition
7
8
using namespace Ogre; // use the Ogre namespace
9
class Paddle
Paddle.h
10 {
11 public:
12
// constructor
13
Paddle( SceneManager *sceneManagerPtr, String paddleName,
14
int positionX );
15
~Paddle(); // destructor
16
void addToScene();
17
void movePaddle( Vector3 direction ); // move a Paddle
Where to place the Paddle
// add a Paddle to the scene
Provide a name for the Paddle’s
node to avoid name clashes
18
19 private:
Move the Paddle in the
20
SceneManager* sceneManagerPtr; // pointer to the SceneManager
given direction
21
SceneNode *nodePtr; // pointer to a SceneNode
22
String name; // name of the Paddle
23
int x; // x-coordinate of the Paddle
24 }; // end of class Paddle
25
26 #endif // PADDLE_H
2008 Pearson Education,
Inc. All rights reserved.
1
// Paddle.cpp
2
3
// Paddle class member-function definitions.
#include <Ogre.h> // Ogre class definition
4
5
using namespace Ogre; // use the Ogre namespace
6
7
8
#include "Paddle.h" // Paddle class definition
// constructor
9 Paddle::Paddle( SceneManager *ptr, String paddleName,
10
int positionX )
11 {
12
13
45
Outline
Paddle.cpp
(1 of 2)
sceneManagerPtr = ptr; // set the pointer to the SceneManager
name = paddleName; // set the Paddle's name
14
x = positionX; // set the Paddle's x-coordinate
15 } // end Paddle constructor
16
17 // destructor
18 Paddle::~Paddle()
19 {
20
// empty body
21 } // end Paddle default destructor
22
2008 Pearson Education,
Inc. All rights reserved.
23 // add the Paddle to the scene
46
24 void Paddle::addToScene()
Outline
25 {
26
27
Entity *entityPtr = sceneManagerPtr->
createEntity( name, "cube.mesh" ); // create an Entity
28
entityPtr->setMaterialName( "paddle" ); // set the Paddle's material
29
30
entityPtr->setNormaliseNormals( true ); // fix the normals when scaled
nodePtr = sceneManagerPtr->getRootSceneNode()->
31
createChildSceneNode( name ); // create a SceneNode for the Paddle
32
nodePtr->attachObject( entityPtr ); // attach Paddle to the SceneNode
33
nodePtr->setScale( .02, .3, .1 ); // set the Paddle's size
34
nodePtr->setPosition( x, 0, 0 ); // set the Paddle's position
35 } // end function addToScene
36
Paddle.cpp
(2 of 2)
Set the Paddle’s position
37 // move the Paddle up and down Move
the screen
the Paddle
in the
38 void Paddle::movePaddle( Vector3 direction )
given direction
39 {
40
nodePtr->translate( direction ); // move the Paddle
41
42
if ( nodePtr->getPosition().y > 52.5 ) // top of the box
nodePtr->setPosition( x, 52.5, 0 ); // place Paddle at top of box
43
else if ( nodePtr->getPosition().y < -52.5 ) // bottom of the box
44
45 Keep the
// Paddle
place thefrom
Paddle
at the bottom of the box
going
46
nodePtr->setPosition(
out of
the playing area
x, -52.5, 0 );
47 } // end function movePaddle
2008 Pearson Education,
Inc. All rights reserved.
47
23.4.3 Adding to the Scene
• An Entity is an instance of a mesh within the
scene
– A mesh is a file that contains the geometry information of a
3D model.
– Each Entity object must have a unique name.
1992-2008 Pearson Education, Inc. All rights reserved.
48
23.4.3 Adding to the Scene (Cont.)
• A material is used to color an Entity
– Usually created with a script (text file with a .material
extension), though it can be created directly in the program
– Structure looks similar to C++ code, with curly braces
enclosing each section
– A material file can define multiple materials
– Each material defined must have a unique name
1992-2008 Pearson Education, Inc. All rights reserved.
49
23.4.3 Adding to the Scene (Cont.)
• A SceneNode encapsulates an object within the
scene graph
– Each one must have a unique name
– May have many children but only one direct parent
– Positioned at parent’s origin by default
1992-2008 Pearson Education, Inc. All rights reserved.
50
23.4.3 Adding to the Scene (Cont.)
•Overlay
– Renders on top of the scene
– Usually defined with a script—a text file with a .overlay
extension
– Composed of OverlayElements
• OverlayContainer may hold any OverlayElement
• TextAreaOverlayElement displays text
• First element must be an OverlayContainer
– Metrics mode
• Pixel mode—size and position declared in pixels
• Relative mode—size and position declared relative to size and
position of parent OverlayContainer (ranges from 0 to 1)
1992-2008 Pearson Education, Inc. All rights reserved.
1
// paddle material definition
2
material paddle
3
{
51
Create a material named paddle
4
// define one technique for rendering a Paddle
5
technique
6
{
7
8
// render a Paddle in one pass
pass
9
{
10
// color the Paddle dark orange
11
ambient 1 0.549 0
12
diffuse 1 0.549 0
13
specular 1 0.549 0 120
16 }
What color light the object reflects
}
14
15
Outline
}
How shiny the object is (any
value greater than 0)
2008 Pearson Education,
Inc. All rights reserved.
1
// wall material definition
2
material wall
3
4
5
6
{
Create a material named wall
Outline
// define one technique for rendering a wall
technique
{
7
8
9
// render a wall in one pass
pass
{
10
// color the wall cyan
11
12
13
14
ambient 0 0.545 0.545
diffuse 0 0.545 0.545
specular 0 0.545 0.545 120
15
16 }
52
What color light the object reflects
}
}
How shiny the object is (any
value greater than 0)
2008 Pearson Education,
Inc. All rights reserved.
1
// An Overlay to display the score
2
Score
3
{
4
5
A higher z-order renders on top
of a lower z-order
PanelOverlayElement container to hold the
7
8
// create a
container Panel(ScorePanel)
9
{
15
16
17
18
19
20
21
22
23
24
25
Outline
Create an Overlay named Score
// set a high z-order, displays on top of anything with lower z-order
zorder 500
6
10
11
12
13
14
53
text areas
Create a PanelOverlayElement
(a container) called ScorePanel
position this container at the
// use relative metrics mode to
// top-left corner of the screen
metrics_mode relative
Size and position relative
left 0.0
(the window)
top 0.0
Place the top-left corner at (0, 0)
(1 of 3)
to parent
// make it 1/10 the height and the full width of the screen
width 1.0
height 0.1
100% of the window’s width,
10% of the height
// create a TextAreaOverlayElement to display player 1's score
element TextArea(left)
Create a TextAreaOverlayElement
{
leftto the container
// position and size the element called
relative
metrics_mode relative
Size and position relative to parent
(the PanelOverlayElement)
2008 Pearson Education,
Inc. All rights reserved.
26
// position it at the top of the container 5% from the left and
27
// make it the same height and half as long as the container
28
29
left 0.05
top 0.0
30
31
32
33
34
width 0.5
height 1.0
35
char_height .05
36
37
colour 1.0 0 0
caption Player 1 Score:
Outline
Position and size the
TextAreaOverlayElement
// set font used for caption and set the size and color
font_name BlueBold
Use the BlueBold font
Set the character height
Make the text red
0
The text to display
38
39
40
}
// create a TextAreaOverlayElement to display player 2's score
element TextArea(right)
41
42
{
43
44
54
(2 of 3)
// position and size the element relative to the container
metrics_mode relative
2008 Pearson Education,
Inc. All rights reserved.
45
// position it at the top of the container 69% from the left and
46
// make it the same height as the container, stretch to the end
47
left 0.69
48
top 0.0
49
width 0.5
50
height 1.0
55
Outline
51
52
// set font used for caption and set the size and color
53
font_name BlueBold
54
char_height 0.05
55
colour 1.0 0 0
56
caption Player 2 Score: 0
}
57
58
(3 of 3)
}
59 }
2008 Pearson Education,
Inc. All rights reserved.
1
2
// define the BlueBold font
BlueBold
3
4
5
{
56
Create a font name BlueBold
// define the font type
type truetype
Outline
This is a “true type” font
6
7
8
// set the source file for the font
source bluebold.ttf
9
10
// set the font size
The font file
11
12
size 16
13
14
15 }
// set the font resolution (96 is standard)
resolution 96
The font size (16 pt)
The font’s resolution
2008 Pearson Education,
Inc. All rights reserved.
1
// An Overlay to display "Game Paused" when the player pauses the game
2
PauseOverlay
3
{
4
5
57
Outline
// set a high z-order, displays on top of anything with lower z-order
zorder 500
6
7
8
9
10
11
12
13
14
// create a PanelOverlayElement container to hold the text area
container Panel(Pause)
Create a PanelOverlayElement
{
Pause
// use relative metrics mode to called
position
and size this container
metrics_mode relative
// place the container at the
left 0.0
(1 of 2)
Size and position it relative to
its parent
window)
top-left
corner(the
of the
window
15
16
17
18
19
20
top 0.0
21
22
23
// create a TextAreaOverlayElement to display the text
element TextArea(pauseText)
Create a TextAreaOverlayElement
{
24
25
// make the container the same size as the window
width 1.0
height 1.0
called
// position and size the element relative
topauseText
its container
metrics_mode relative
Size and position it relative to its
parent (the Pause container)
2008 Pearson Education,
Inc. All rights reserved.
26
58
27
// center it vertically in the container
28
vert_align center
29
30
// put the left
31
// make it 2/10
32
33
left 0.4
width 0.2
34
height 0.1
Outline
Vertically center the
TextAreaOverlayElement
corner 4/10 from
the left of the container and
in container
the container
the width of the
and 1/10 the height
Position the top-left corner 40% in from
the left side of the parent container
(2 of 2)
35
36
// set the font used for caption and set the size and color
37
font_name BlueBold
38
char_height 0.05
39
colour 0 0 0
40
caption Game Paused
}
41
42
Use the BlueBold font
Make the text black
The text to display
}
43 }
2008 Pearson Education,
Inc. All rights reserved.
59
23.4.4 Animation and Timers
• Moving a SceneNode
– translate function takes a Vector3—a threedimensional vector type defined by Ogre
– Translations are done in parent space by default—
translated with respect to its parent node’s position and
orientation
– Translations in world space are done with respect to the
origin of the scene (0, 0, 0)
– Translations in local space are done with respect to the
node’s origin
1992-2008 Pearson Education, Inc. All rights reserved.
60
23.4.4 Animation and Timers (Cont.)
• The direction of the Ball is determined by a
Vector3—each value represents a distance
along the x-, y- or z-axis.
– Reverse a direction by changing the sign of the
corresponding component in the vector
1992-2008 Pearson Education, Inc. All rights reserved.
61
23.4.4 Animation and Timers (Cont.)
• A FrameListener is a class that processes
Ogre::FrameEvents.
– A FrameEvent occurs every time a frame begins or ends.
– Every FrameListener has two functions—
frameStarted and frameEnded
• Ogre keeps rendering frames until one of these functions
returns false
1992-2008 Pearson Education, Inc. All rights reserved.
62
23.4.5 User Input
• Ogre does not directly support user input
• The SDK includes Object Oriented Input System
(OIS)
– The InputManager is used to create the various input
devices.
– We create a Keyboard object which represents the actual
keyboard.
– A KeyListener responds to input from the keyboard
• KeyEvents are indications that the player has hit a key
1992-2008 Pearson Education, Inc. All rights reserved.
63
Fig. 23.17 | Player 1 scoring a point. (Part 1 of 3.)
2008 Pearson Education, Inc. All rights reserved.
64
Fig. 23.17 | Player 1 scoring a point. (Part 2 of 3.)
2008 Pearson Education, Inc. All rights reserved.
65
Fig. 23.17 | Player 1 scoring a point. (Part 3 of 3.)
2008 Pearson Education, Inc. All rights reserved.
66
Fig. 23.18 | The Ball bouncing off the top wall. (Part 1 of 3.)
2008 Pearson Education, Inc. All rights reserved.
67
Fig. 23.18 | The Ball bouncing off the top wall. (Part 2 of 3.)
2008 Pearson Education, Inc. All rights reserved.
68
Fig. 23.18 | The Ball bouncing off the top wall. (Part 3 of 3.)
2008 Pearson Education, Inc. All rights reserved.
69
Fig. 23.19 | The Ball bouncing off the left Paddle. (Part 1 of 3.)
2008 Pearson Education, Inc. All rights reserved.
70
Fig. 23.19 | The Ball bouncing off the left Paddle. (Part 2 of 3.)
2008 Pearson Education, Inc. All rights reserved.
71
Fig. 23.19 | The Ball bouncing off the left Paddle. (Part 3 of 3.)
2008 Pearson Education, Inc. All rights reserved.
1
// PongMain.cpp
2
// Driver program for the game of Pong
3
#include <iostream>
72
Outline
4
5
#include "Pong.h" // Pong class definition
6
7// If running on Windows, include windows.h and define WinMain function
8 #if OGRE_PLATFORM==PLATFORM_WIN32 || OGRE_PLATFORM==OGRE_PLATFORM_WIN32
9 #define WIN32_LEAN_AND_MEAN
Include the necessary Windows headers
10 #include "windows.h"
theWinMain
program is
running on
and Check
define ifthe
function
11
PongMain.cpp
(1 of 2)
the Windows platform
12 int WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT )
13
14 // If not, define normal main function
15 #else
16 int main( int argc, char **argv )
17 #endif
18 {
Define a normal main function if not
running on Windows platform
Create the Pong object—will throw
an exception if user cancels the
settings
dialog box
a Pong
object
19
20
21
try
{
Pong game; // create
22
23
game.run(); // start the Pong game
} // end try
Start running a game of Pong
2008 Pearson Education,
Inc. All rights reserved.
24
73
25
catch ( std::runtime_error &error )
26
27
{
#if OGRE_PLATFORM==PLATFORM_WIN32 ||
OGRE_PLATFORM==OGRE_PLATFORM_WIN32
Catch a runtime_error
MessageBoxA( NULL, error.what(), "Exception Thrown!",
by the Pong constructor
MB_OK | MB_ICONERROR | MB_TASKMODAL );
#else
std::cerr << “Exception Thrown: “ << error.what() << std::endl;
#endif
28
29
30
31
32
33
34
35
Outline
thrown
PongMain.cpp
(2 of 2)
If
running
on Windows, display the error
} //
end catch
message is a pop-up
boxon Windows, use
If notdialog
running
return 0;
36 } // end main
the standard error stream
2008 Pearson Education,
Inc. All rights reserved.
74
23.4.5 Collision Detection
• There are Ogre binding for several collision and
physics libraries
– Open Dynamics Engine (ODE, www.ode.org/)
– Bullet (www.continuousphysics.com/Bullet/)
– Newton Game Dynamics (www.newtondynamics.com/)
– PhysX (www.ageia.com)
1992-2008 Pearson Education, Inc. All rights reserved.
75
23.4.5 Sound
• Ogre does not support sound
• OgreAL is a wrapper around the OpenAL audio
library
– Integrate sound functionality into the Ogre code
– SoundManager class used to manage OgreAL objects
• There can be only one SoundManager
– Sound objects contain the sound data
– Attach Sounds to SceneNodes
– Each Sound must have a unique name
– A Sound must finish playing before it can be played again
1992-2008 Pearson Education, Inc. All rights reserved.
76
23.4.5 Resources
• Ogre programs use various external resources
– Scripts to create Materials and Overlays
– .mesh files to represent 3D objects
– OgreAL uses sound files
• Use a ResourceGroupManager to manage a
programs resources
• Ogre will throw a runtime exception if you try to
use a resource that hasn’t been loaded
1992-2008 Pearson Education, Inc. All rights reserved.
© Copyright 2026 Paperzz