Jump to content

Collision fires twice even though clearCollision() is called


ChubbRck
 Share

Recommended Posts

Hi all, I'm having an issue where I want to just sense for a collision once and then deactivate one of the physics bodies. But for the life of me, sometimes the collision fires twice or more times, despite my using clearCollision(). Here's what I have:

 

First I set up a collision between the 'iceCube' and the 'basket':

iceCube.body.collides(basketCollisionGroup, iceCubeCollision, this);

Next, my callback function looks like this:

function iceCubeCollision(body1, body2){   console.log("Ice cube collision")   body1.clearCollision(true);   body1.clearShapes();   console.log ("collision cleared?")   ...}

Does anyone have any advice? Maybe I'm missing something simple like just checking for a 'collision begin' phase? Any help is appreciated -

 

Nick

Link to comment
Share on other sites

This is likely due to the separation and asynchronous nature of the physics calculations and indeed any real-time app in general. Setting a flag on the object and checking for that flag on the collision should ensure your routine only gets called once:

function iceCubeCollision(body1, body2){  if (!body1.hasCollided) { // check to see if the 'hasCollided' property is not 'truthy' (i.e. not set, or set to false or null or 0 or something)   console.log("Ice cube collision")   body1.hasCollided = true; // set it to true so if the collision happens again, everything inside this if statement will be skipped   ...  }}

The 'hasCollided' bit can be named whatever you want, and could even be a number that's incremented each time to allow you to do different things depending on how many collisions happen etc.

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...