Phaser 3/matter physics bridge

hi again,
i’m putting together a platformer using the phaser 3 template and matter physics. i’ve set up a bridge based on this example:

[https://labs.phaser.io/edit.html?src=src/physics/matterjs/bridge.js]

but for the life of me i cant attach images or sprites to the rectangles in this bit of code (at least i think it should go here)

var bridge = this.matter.add.stack(160, 290, 15, 1, 0, 0, function(x, y) {
    return Phaser.Physics.Matter.Matter.Bodies.rectangle(x - 20, y, 53, 20, { 
        collisionFilter: { group: group },
        chamfer: 5,
        density: 0.005,
        frictionAir: 0.05
    });
});

anybody have an idea of how to do this?

ps. it was easy enough to use a soft body with a few columns and one row, but i cant adapt the idea to the bridge example.

1 Like

I was struggling with the same thing today. If someone is familiar with phaser + matterjs, please also demonstrate how to add a simple fillStyle or fillColor to the bodies of the bridge.

1 Like

I just figured out a way to do it. I have no idea if it could be done better and easier. I actually only use matter methods provided by phaser like this.matter... and not the “pure” Phaser.Physics.Matter.Matter... ones.

Here is how it look:
myimage

Here is the tile I used:
tile

And here is the code:

  create() {
    console.log('Matter: ', this.matter)

    this.matter.world.setBounds()
    this.matter.add.mouseSpring({})
    let group = this.matter.world.nextGroup(true)

    // creates a new wood plank
    const newWoodPlank = (x: number, y: number) => {
      return this.matter.add
        .image(x, y, 'tile')
        .setBody(
          { type: 'rectangle' },
          { collisionFilter: { group: group }, chamfer: 5, density: 0.005, frictionAir: 0.05 }
        )
    }

    let woodPlanksPositions = []
    let BRIDGE_LENGTH = 18 // needs 18 wood planks for the entire bridge

    // calculate the positions of all wood planks
    for (let i = 0; i < BRIDGE_LENGTH; i++) woodPlanksPositions.push({ x: 150 + i * 50, y: 250 })

    // make all the wood planks
    let woodPlanks = woodPlanksPositions.map(pos => newWoodPlank(pos.x, pos.y))

    // attaching each plank to the next one
    for (let i = 0; i < woodPlanks.length - 1; i++) {
      this.matter.add.constraint(woodPlanks[i], woodPlanks[i + 1], 10, 1, {
        pointA: { x: 20, y: 0 },
        pointB: { x: -20, y: 0 }
      })
    }

    // attaching the first plank to the left side
    this.matter.add.worldConstraint(woodPlanks[0], 2, 0.9, {
      pointA: { x: 140, y: 300 },
      pointB: { x: -25, y: 0 }
    })

    // attaching the last plank to the right side
    this.matter.add.worldConstraint(woodPlanks[woodPlanks.length - 1], 2, 0.9, {
      pointA: { x: 1100, y: 300 },
      pointB: { x: 25, y: 0 }
    })
  }

thanks yannick, logical once i see it written down. this matter stuff is pretty cool.

thank you, I was literally about to ask this question on the discord server