Understanding NAPE collision detection

One of the features which highly contribute to the success of a physics engine is the collision detection.

NAPE has a robust collision detection, although you won’t find that much information around the web, that’s why this blog is a must read :)

To explain the basics of NAPE collision detection, I stripped the Hundreds game prototype and now I only have one ball running around the stage and bouncing off walls.

I will show you how to detect collision between the ball and the walls.

Look at the result:

Each time the balls bounce off the walls, the stage color changes.

This is the script:

Let’s comment line by line what’s involved in collision detection:

Line 20: defining an interaction listener. Since a collision is an interaction, we need to define it at first.

Lines 21-22: these are Callback Types, and I am going to use them in a smart way to detect only some kind of collisions. Think about a Callback Type like a built-in Box2D collision filtering, if you are used to it.

Line 25: the core of the script: the Interaction Listener. You can handle any type of interaction with it, but since I am looking for collisions, here is the list of arguments:

CbEvent.BEGIN: the event type to listen for, in this example the begin of the event.

InteractionType.COLLISION: the interaction type to listen for, in this example a collision.

wallCollisionType: the OptionType to match first Interactor against, in this case the wall collision type

ballCollisionType: the OptionType to match second Interactor against, in this case the ball collision type

ballToWall: the callback function

Line 26: at this time, the newly created listeners is added to the NAPE world.

Line 44: this is how I add the ball to its Callback Type

Line 58: same thing for the wall.

And that’s it. No need to download any source code, just copy/paste it in the Hundreds game prototype source code.

  • Pingback: Understanding NAPE collision detection – Emanuele Feronato « eaflash()

  • Thank you, this helped! but I have a question for you, do you know how to add your own object to the “collision:InteractionCallback” in order to affect objects beyond the scope of nape? such as the hp of a character when it gets hit by a projectile.

  • Walter, Nape body objects have a property called userData (though for some reason it doesn’t appear in the documentation) but you can put any user created data in it.

    Just access it like so:

    myBody.userData.myUniqueVariable = myCharacter;

    Hope that helps!

  • Hey Justin, I am glad to say I was able to get to that exact solution, thanks a lot :)