OpherV Posted April 20, 2014 Share Posted April 20, 2014 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 More sharing options...
Wavertron Posted April 20, 2014 Share Posted April 20, 2014 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 More sharing options...
OpherV Posted April 21, 2014 Author Share Posted April 21, 2014 Ok but regardless of my sprite placement methods, how can I check for overlap in the create state? Link to comment Share on other sites More sharing options...
OpherV Posted May 3, 2014 Author Share Posted May 3, 2014 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 suppliedThen 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; } } } } jpdev 1 Link to comment Share on other sites More sharing options...
Recommended Posts