Pavan K
Pavan K

Reputation: 4693

bounding polygon of a sprite from pixi to p2

I am importing a sprite into PIXI using

var texture= PIXI.Texture.fromImage("img.png");
var sprite = new PIXI.Sprite(texture);
// I set the position
stage.addChild(sprite);

I want to detect collisions on this sprite and since PIXI has no collision detection support. I am using p2.js and this needs a polygon bounding box for collision detection

How can I get the polygon from pixi and pass it to p2 and detect a collision?

Any sample or some pointers will be very helpful.

Upvotes: 3

Views: 1447

Answers (1)

schteppe
schteppe

Reputation: 2084

p2.js and Pixi.js have different coordinate systems, which makes the solution a bit complex. The "up" direction in p2.js is along the positive Y axis and in Pixi it's along negative Y. To get around this, one solution is to apply a negative scale to the Pixi stage to flip it upside down:

stage.scale.y = -1;

You need to add a p2.Body for each sprite. To transfer position and rotation data from Pixi.js sprites to p2.js bodies, do this:

body.position[0] = sprite.position.x;
body.position[1] = sprite.position.y;
body.angle = sprite.rotation;

To track overlaps you need to add contact listeners:

world.on('beginContact', function(evt){
    // evt.bodyA and evt.bodyB started overlapping!
});

world.on('endContact', function(evt){
    // evt.bodyA and evt.bodyB are not overlapping any more.
});

See this example: http://jsfiddle.net/18shpxq8/2/

Upvotes: 4

Related Questions