Trying out complex shapes with Matter physics engine (Phaser3)

This article can be read in about 3 minutes.
PR

The purpose 

Try using Matter.js to utilize a physics engine with complex shapes in Phaser 3.

PR

Prepare data

Prepare image

Prepare PNG image

For this example, I created the image above. It’s a bit hard to see, but the white areas are transparent.

I’ve named it c.png, and its dimensions are 100×100 pixels.

PR

Implementation

Load image

The aforementioned image is loaded during the scene’s preload.

    preload ()
    {
        this.load.image('c', 'assets/c.png');
    }

Add image

add the image above to the scene in create() function.

    create ()
    {
        const poly = this.add.image(300, 300, 'c');

region setting

Set a collision detection area on the image added above.

        const chevron = '0 0 ' +     //①の(x,y)
                        '100 0 ' +    //②の(x,y) 
                        '100 100 ' +      //③の(x,y)
                        '80 100 ' +       //④の(x,y)     
                        '80 20 ' +        //⑤の(x,y)
                        '20 20 ' +        //⑥の(x,y)
                        '20 100 ' +       //⑦の(x,y)
                        '0 100 ' +        //⑧の(x,y)
                        '0 0';            //⑨の(x,y)(1個目と同じ)
        this.matter.add.gameObject(poly, { shape: { type: 'fromVerts', verts: chevron, flagInternal: true } });
 

The string will be set with x y values, space-separated, in the order shown in Figure ① through ⑨.

matter.add.gameObject links the image (poly) and chevron point sequence.” This is shorter and more direct.

PR

Result

We are able to set the collision detection as follows

180°回転し別のオブジェクトを入れることも可能です。

comment

Copied title and URL