i´m starting with phaser arcade physics. the assigned categories won´t work - i have to add a collider manually. the bricks should also collide with each other:
for (let i = 0; i < 3; i++) {
const brick = this.physics.add
.sprite(300 + 100 * i, 300 + 100 * i, '')
.setSize(150, 30 * (i + 1))
.setMass(1)
.setFriction(0)
.setMaxVelocity(0, MaxVelocityY)
.setCollideWorldBounds(true)
.setCollisionCategory(CollisionCategory.BRICK)
.setCollidesWith([CollisionCategory.PLAYER, CollisionCategory.BRICK]); // not working
//add collider manually
this.physics.add.collider(this.player, brick);
}
categories:
enum CollisionCategory {
PLAYER = 1 << 1,
BRICK = 1 << 2,
}
Are there some additional options needed?
I say it works as designed, and everything is correct, but there are some thing to note here:
this.physics.nextCategory();
link to the documentationsetCollisionCategory
and setCollidesWith
just tells the physics engine the check the collision between hte object marked in the specific categories, you still have to invoke this.physics.add.collider
or some other function.Short Demo:
(ShowCasing how the engine now just check agains categories)
class DemoScene extends Phaser.Scene {
create() {
this.add.text(10, 10, "White and red collide, green doesn't.\nBlue collides only with white").setOrigin(0);
let box1 = this.add.rectangle(10, 45, 20, 20, 0xffffff).setOrigin(0);
let box2 = this.add.rectangle(200, 45, 20, 20, 0xff0000).setOrigin(0);
let box3 = this.add.rectangle(300, 45, 20, 20, 0x00ff00).setOrigin(0);
let box4 = this.add.rectangle(350, 45, 20, 20, 0x0000ff).setOrigin(0);
let cat1 = this.physics.nextCategory();
let cat2 = this.physics.nextCategory();
let cat3 = this.physics.nextCategory();
this.physics.add.existing(box1).body.setCollisionCategory(cat1).setCollidesWith([cat1, cat2]);
this.physics.add.existing(box2).body.setCollisionCategory(cat2).setCollidesWith([cat1, cat2]);
this.physics.add.existing(box3).body.setCollisionCategory(cat3).setCollidesWith([cat3]);
this.physics.add.existing(box4).body.setCollisionCategory(cat1).setCollidesWith([cat1]);
box1.body.setVelocity(30, 0);
box2.body.setVelocity(-30, 0);
box3.body.setVelocity(-30, 0);
box4.body.setVelocity(-30, 0);
// letting all object collide
this.physics.add.collider([box1, box2, box3, box4], [box1, box2, box3, box4]);
}
}
var config = {
width: 540,
height: 180,
physics: {
default: 'arcade',
arcade: { debug: true },
},
scene: DemoScene,
};
new Phaser.Game(config);
console.clear();
document.body.style = 'margin:0;';
<script src="//cdn.jsdelivr.net/npm/phaser/dist/phaser.min.js"></script>
I never needed (really used) this features, since I think it is only good to differentiate nuances in collision, that level of detail I never needed. The main benefit I see is, if you want to change dynamically which objects collide with each other, then this feature would be helpful since you would only have to change the category (and maybe for performance, but this I'm just assuming).