Jump to content

Collision fires twice even though clearCollision() is called


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 -



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

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Recently Browsing   0 members

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