Game Development Reference
In-Depth Information
Applying impulses
Next, we'll work through an example of an impulse by creating a small explosive force
at the location of the mouse cursor. In order to simulate an explosion, we will need
to create a spherical trigger volume, instead of a box (since a box-shaped explosion
would be really weird). When collisions are detected with this volume we can apply
an impulse that points from the center of the explosion towards the target object(s),
forcing the object away from its epicenter. However, we only want this object to linger
for a single simulation step, so that we can tightly control the amount of acceleration
applied to the target objects.
Since we want our explosion to be generated only temporarily when a key is pressed,
this presents a problem when we interact with the Keyboard() command, since it is
called once when a key is pressed, and continuously while the key is still held down.
It's possible to tweak our input system to not repeat calls like this with a FreeGLUT
function call (as mentioned previously in Chapter 1 , Building a Game Application ), but
our camera moving code currently depends on the current style, so changing it now
would cause a different set of problems.
So, what we can do is use a simple Boolean flag that tells us if we can create an
explosion object. When we want to create an explosion, we will check if the flag is
true. If so, we create the explosion and set the flag to false, and we will not set the
flag back to true again until the key is released. This prevents subsequent calls to the
Keyboard() function from creating another explosion trigger volume unless we de-
tect a key up event.
This is a fairly straightforward process, and the source code for this chapter adds
the relevant code to produce this effect with slight tweaks to the Keyboard() , Key-
boardUp() , UpdateScene() , and CollisionEvent() functions of BasicDemo .
The 3D math implemented in the code uses some simple vector arithmetic to obtain
the final direction by converting the vector between them into a unit vector, and ob-
taining the final magnitude from the distance between the objects and some constant
value ( EXPLOSION_STRENGTH ). With a direction and a magnitude, we can create our
final impulse vector.
Launch the application, place the mouse cursor somewhere near the boxes, and
press the E key. This will result in an invisible explosion that pushes all the nearby
objects away through a simple impulse force. The following screenshot shows what
Search WWH ::

Custom Search