Tuesday, March 27, 2012

Havok Tutorial: Detect a ball bounce.

So lets say you have several balls bopping around your scene. Or heads. Or grenades. Whatever. And you need to do something every time one of the balls bounces ( off of the ground, a wall, etc ), like play a sound effect.

You'll want to check out the Havok demos at  \Demo\Demos\Physics\Api\Collide\ContactPointCallbacks\EndOfStepCallback. Overriding the hkpContactListener class will give you the ability to launch a callback every time a rigidbody with that listener equipped experiences a collision.

Here is some code...

// Define our derived class for collision call backs.
class MyEndOfStepListener : public hkReferencedObject, public hkpContactListener
{
public:
 HK_DECLARE_CLASS_ALLOCATOR( HK_MEMORY_CLASS_DEMO );

 void collisionAddedCallback( const hkpCollisionEvent& event )
 {
  registerForEndOfStepContactPointCallbacks( event );
 }

 void collisionRemovedCallback( const hkpCollisionEvent& event )
 {
  unregisterForEndOfStepContactPointCallbacks( event );
 }

 void contactPointCallback( const hkpContactPointEvent& event )
 {
  if ( event.m_contactPointProperties->m_flags & hkContactPointMaterial::CONTACT_IS_NEW )
  {
   if(  hkpContactPointEvent::TYPE_MANIFOLD_AT_END_OF_STEP )
    my_func();
  }
 }
};

// Create the listener.
MyEndOfStepListener* m_listener = new MyEndOfStepListener();

// Create the rigid body
hkpRigidBody* rb = new hkpRigidBody(bodyCinfo);

// Set our listener.
rb->addContactListener( m_listener );

// Clean up when done.
rb->removeContactListener( m_listener );


Now of course you can extend this technique to detecting various kinds of collisions by using this and other collision listener types. Check out the demos, they will give you great ideas.

No comments:

Post a Comment