User Tools

Site Tools


en:guides:beginners:collision_events

Part 15 - Collision Events

In order for the game to be won by the hero by collecting the star, we need to create a Physics Event Handler in code to check for, and to process a collision between those two objects.

We can declare one at the bottom of the Init() function:

orxViewport_CreateFromConfig("MainViewport");
 
orxEvent_AddHandler(orxEVENT_TYPE_PHYSICS, PhysicsEventHandler);

What this means is, every time there is a physics event like a collision, execute the PhysicsEventHandler function. We don't have one of these, so you can add one:

orxSTATUS orxFASTCALL PhysicsEventHandler(const orxEVENT *_pstEvent)
{
 
    return orxSTATUS_SUCCESS;
}

The type of event we are interested in for collisions is the orxPHYSICS_EVENT_CONTACT_ADD.

Add this code inside the new function:

orxSTATUS orxFASTCALL PhysicsEventHandler(const orxEVENT *_pstEvent)
{
  if (_pstEvent->eID == orxPHYSICS_EVENT_CONTACT_ADD) {
    orxOBJECT *pstRecipientObject, *pstSenderObject;
 
    pstSenderObject = orxOBJECT(_pstEvent->hSender);
    pstRecipientObject = orxOBJECT(_pstEvent->hRecipient);
 
    orxSTRING senderObjectName = (orxSTRING)orxObject_GetName(pstSenderObject);
    orxSTRING recipientObjectName = (orxSTRING)orxObject_GetName(pstRecipientObject);
 
    if (orxString_Compare(senderObjectName, "StarObject") == 0){
        //do something
    }
 
    if (orxString_Compare(recipientObjectName, "StarObject") == 0){
        //do something
    }
  }
  return orxSTATUS_SUCCESS;
}

Whenever there is contact between two objects, orxPHYSICS_EVENT_CONTACT_ADD is the physics event ID that will trigger. Both the sender object and the recipient object are available to us in the event package.

Next, we can check if the name of either object is “StarObject”. And if so, the game will be won.

Replace the “do something” lines with a command that will instantly remove the star from the game:

if (orxString_Compare(senderObjectName, "StarObject") == 0){
    orxObject_SetLifeTime(pstSenderObject, 0);
}
 
if (orxString_Compare(recipientObjectName, "StarObject") == 0){
    orxObject_SetLifeTime(pstRecipientObject, 0);
}

The one last thing to add to ensure the collision between the star and the hero works, is to add “star” to the HeroBody check mask:

[HeroBodyPart]
Type        = box
Solid       = true
SelfFlags   = hero
CheckMask   = platforms # star

Checkmasks and flags must work both ways, that is, it must be defined on both object bodies.

Compile and run. Make your way up to the top platform and the star should disappear when the hero touches it:


Next: Part 16 – Jelly Monsters.

en/guides/beginners/collision_events.txt · Last modified: 2024/11/19 02:24 (5 weeks ago) by sausage