EPhysics - Collision Detection

The purpose of this example is to demonstrate the EPhysics Collision Detection usage - The code adds two balls, one with impulse and the second with a collision detection callback, to show an effect.

collision_detection.png

For this example we'll have an EPhysics_World, and two basic EPhysics_Bodys, we'll apply an impulse in one of then and the other will be stopped "waiting" for a collision.

The basic concepts like - initializing an EPhysics_World, render geometry, physics limiting boundaries, add an Ephysics_Body, associate it to evas objects, change restitution, friction and impulse properties, were already covered in EPhysics - Bouncing Ball

Collision Data Struct

While in this example we'll be working with a struct to hold some objects in our code. For clarity sake we present you the struct declaration in the following block.

struct _Collision_Data {
Test_Data base;
Evas_Object *impact;
EPhysics_Body *sphere;
EPhysics_Body *sphere2;
};

Adding the Callback

Calling ephysics_body_event_callback_add() will register a callback to a type of physics body event.

EPHYSICS_CALLBACK_BODY_COLLISION : called just after the collision has been actually processed by the physics engine. In other words, to be notified about a collision between two physical bodies.

ephysics_body_event_callback_add(collision_data->sphere,
_collision_cb, collision_data);

See _EPhysics_Callback_Body_Type for more event types.

Collision Function

The callback function will filter the collision to be sure if that body is which we want and then show the effect.

First we need to create a specific variable type to get collision infos: EPhysics_Body_Collision

_collision_cb(void *data, EPhysics_Body *body __UNUSED__, void *event_info)
{
EPhysics_Body *contact_body;
Collision_Data *collision_data = data;
EPhysics_Body_Collision *collision = event_info;
int x, y, z;

Now we want to know which body collides with and filter it.

contact_body = ephysics_body_collision_contact_body_get(collision);
if (contact_body != collision_data->sphere2) return;

We just get the collision position, move the impact effect to this coordinate and send a signal to edje to show it.

ephysics_body_collision_position_get(collision, &x, &y, &z);
evas_object_move(collision_data->impact, x - 10, y - 40);
elm_object_signal_emit(collision_data->impact, "impact,show",
"ephysics_test");
}

Here we finish the example. The full source code can be found at test_collision_detection.c.