我有一个玩家对象(Matter/Sprite),我想添加一个底部传感器主体,以检测玩家是否撞到地面或砖块(例如启用跳跃)。我准备玩家主体:私人
我有一个玩家对象(Matter/Sprite),我想添加一个底部传感器体来检测玩家是否撞到地面或砖块(例如启用跳跃)。
我准备了玩家主体:
private preparePhysicsBody() {
const bodyPlayer = this.scene.matter.bodies.rectangle(
this.displayWidth / 2, this.displayHeight / 2,
this.displayWidth, this.displayHeight);
bodyPlayer.collisionFilter.category = PhysicsBodyCategories.PLAYER;
bodyPlayer.collisionFilter.mask = PhysicsBodyCategories.WORLD;
const bodyPlayerBottomSensor = this.scene.matter.bodies.rectangle(
bodyPlayer.position.x, bodyPlayer.position.y + (this.displayHeight / 2),
this.displayWidth - 6, 1, {
isSensor: true
});
bodyPlayer.collisionFilter.category = PhysicsBodyCategories.PLAYER_BOTTOM;
bodyPlayer.collisionFilter.mask = PhysicsBodyCategories.WORLD | PhysicsBodyCategories.BRICK;
const body = this.scene.matter.body.create({
parts: [
bodyPlayerBottomSensor,
bodyPlayer
]
});
this.setExistingBody(body);
this.setFixedRotation();
//on collisions
this.setOnCollide((obj: MatterCollisionData) => {
console.log(obj.bodyA.collisionFilter.category)
console.log(obj.bodyB.collisionFilter.category)
});
以及处于不同位置的一些砖块(也是 Matter/Sprite):
class Brick extends Sprite {
constructor(scene: Scene, x: number, y: number) {
super(scene.matter.world, x, y, "brick", undefined, {
isStatic: true
});
this.setPosition(x, y);
this.setFriction(0.01)
this.setDisplaySize(100, 10)
this.setCollisionCategory(PhysicsBodyCategories.BRICK)
第一个问题是,尽管只有 WORLD 分配给 mask,playerBody 仍然会与砖块发生碰撞。
第二个问题是 setOnCollide 没有触发。
我也尝试使用 playerObject 的初始生成的主体,并为类别和掩码设置相同的值,并且它起作用了,碰撞检测也触发了。