Jump to content

How to check overlap in P2 physics?


OpherV
 Share

Recommended Posts

At the start of the game I'm placing my sprites randomly.

For each new sprite I'd like to check overlap against existing sprites.

Is there an overlap method for P2 physics?

 

I can't use the collides function with a callback since this is the create stage - the game loop hasn't started yet at this point.

Link to comment
Share on other sites

I'd suggest using a more controlled sprite placement during Create such that there will never be an overlap. eg Generate an x,y and create a new Phaser.Point. Check its distance against all existing sprite positions. If its too close just generate a new random x,y until you find a safe spot. The distance check won't be a pixel perfect overlap check but should be good enough for what you want.

Link to comment
Share on other sites

  • 2 weeks later...

I found a solution!

 

the trick is to make sure you update sprite.body.x\sprite.body.x.

Then you need to call sprite.body.data.updateAABB(), which in turns allows you to use sprite.body.data.aabb.overlaps()

 

My function takes a placement function, or places the sprite either randomly if no placement function is supplied

Then it checks against the sprites in the spriteArray, and replaces if a collision occurs.

If no successful placement is met after maxAttempts, the functions just exits.

(this is to make sure no infinite loops occur when no proper placement can be found)

 

 

Here's the function:

    function _placeWithoutCollision(sprite,spriteArray,placeFunction){        if (!placeFunction){            placeFunction=function(sprite){                sprite.body.x=game.world.randomX;                sprite.body.y=game.world.randomY;            }        }        var isColliding=true;        var maxAttempts=10; //the number of attempts to place without collision        var placeAttemptCounter=0;        while (isColliding && placeAttemptCounter<maxAttempts){            //no collision, end loop            isColliding=false;            placeFunction(sprite);            placeAttemptCounter++;            sprite.body.data.updateAABB();                for(var x=0;x<spriteArray.length;x++){                    var checkAgainstSprite=spriteArray[x];                    if(sprite.body.data.aabb.overlaps(checkAgainstSprite.body.data.aabb)){                        //console.log(sprite.id,"colliding");                        isColliding=true;                        break;                    }                }          }    }
Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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