Phaser Box2D中的碰撞

时间:2015-09-21 14:35:47

标签: box2d collision phaser-framework

有人知道如何识别身体内的矩形吗?

示例:

this.myBody = new Phaser.Physics.Box2D.Body(this.game, null, 10, 10);
this.myBody.addRectangle(2, 10, 10 * Math.cos(60), 10 * Math.sin(60), 60);
this.myBody.addRectangle(2, 10, 10 * Math.cos(60), 10 * Math.sin(60), 60);

如果一个物体确实与包含矩形的物体发生碰撞,我怎么知道该物体的矩形碰撞?

感谢。

1 个答案:

答案 0 :(得分:0)

在Box2D中向主体添加矩形时,您需要添加一个装置。我们可以通过其ID识别夹具。

this.myBody = new Phaser.Physics.Box2D.Body(this.game, null, 10, 10);
var fixture1 = this.myBody.addRectangle(2, 10, 10 * Math.cos(60), 10 * Math.sin(60), 60);
this.rect1_id = fixture1.id;
var fixture2 = this.myBody.addRectangle(2, 10, 10 * Math.cos(60), 10 * Math.sin(60), 60);
this.rect2_id = fixture2.id;

然后,我们可以为sprite添加一个碰撞回调。只要身体与该类别中的另一个身体发生碰撞,就会调用此方法。确保设置实体类别。

this.onCollision = function(thisBody, theirBody, thisFixture, theirFixture, begin, contact) {
    // Parameters are:
    // thisBody: the body of the sprite
    // theirBody: the body of the sprite 'thisBody' collided with
    // thisFixture, theirFixture: the fixtures of the bodies that collided
    // begin: whether this was the start of the collision
    // contact: the collision object

    // I'll define what goes in this below
};

var category = 11;
this.body.setCollisionCategory(1);
this.body.setCollisionMask(1);
this.body.setCategoryContactCallback(
  category,
  this.onCollision,
  this
);

最后,调用this.onCollision,我们只需检查灯具的ID,并将其与我们存储在this.rect1_id和this.rect2_id中的值进行比较。

this.onCollision = function(thisBody, theirBody, thisFixture, theirFixture, begin, contact) {
    switch (thisFixture.id) {
    case this.rect1_id:
        console.log('hit the first rectangle!');
        break;
    case this.rect2_id:
        console.log('hit the second rectangle!);
        break;
    default:
        console.log("I don't recognise this fixture.");
    }
};

很抱歉此回复是2岁!我在寻找别的东西时发现了它。