Apply force on CollisionStart event

i’m having problem with matter js when trying to apply force on collission start event.

what i’m trying to do is making a sensor that give force to an object when it collides.

i’ve tried to apply force by object alone it works fine.

but when i try to call apply force within on collision start event. it seems like it doesn’t work, no error, no warning, but there are no difference when sensor hits.

below are function that called on collision start.

 const onCollision = (event) => {
        for (const pair of event.pairs) {
            const bodyA = pair.bodyA;
            const bodyB = pair.bodyB;
            if (!bodyA.isSensor && !bodyB.isSensor) continue;
            const sensor = bodyA.isSensor ? bodyA : bodyB;
            console.log(sensor.label);
            if (sensor.label !== 'upper' && sensor.label !== 'lower') continue
            const item = bodyA.isSensor ? bodyB : bodyA
            if (item.isStatic) continue;
            console.log('trigger')
            console.log(item.gameObject.applyForce)
            const force = 0.5
            const forceAngle = Phaser.Math.DegToRad(0);
            // item.gameObject.applyForce({x: Math.cos(forceAngle) * force, y: Math.sin(forceAngle) * force});
            // item.gameObject.setAngularVelocity(0.1 * modifier);
            item.gameObject.body.force.x += 5;

        }
    }
this.matter.world.on('collisionstart', (event) => {
        onCollision(event)
    });

in case someone stumble on this . . .

i managed to accomplish this by storing the item that collides with sensor in a variable.

const onCollision = (event) => {
    for (const pair of event.pairs) {
        const bodyA = pair.bodyA;
        const bodyB = pair.bodyB;
        if (!bodyA.isSensor && !bodyB.isSensor) continue;
        const item = bodyA.isSensor ? bodyB : bodyA
        if (item.isStatic) continue;
        this.item = item.gameObject;
    }
}

using the variable i apply the force within the update loop. end remove the variable value afterwards.

update = (time, dt) => {
    // this.bar?.update();
    if (!this.item) return;
    const force = 0.005
    const forceAngle = Phaser.Math.DegToRad(0);
    this.item.applyForce({x: Math.cos(forceAngle) * force, y: Math.sin(forceAngle) * force});
    this.item = null;
}

i guess applying force within collision event aren’t working since it happen after matter update loop (?)

Bit late to the party, but I’ve come across the same issue (and solution) a few weeks ago. Apparently this is a known quirk, see applyForce on collisionStart event · Issue #134 · liabru/matter-js · GitHub.

1 Like