javascriptphaser-frameworkphaserjs

Creating a polygon with a texture in Phaser 3 Matter js


In Phaser 3 (using matter JS physics), it seems that there's no way of setting a texture to a polygon, and yet I need to have a hexagon/pentagon with a texture.

I've been unable to figure out how to set a PNG texture of a polygon with the physics of a polygon. How can I do this?

I've already figured out the vertices of a needed polygon, but cannot find a way to create it with a texture attached

const pentagonVertices = [  
  { x: (0) +0.5, y: ((2.01 / 4) + 0.5) },
  { x: (1.91 / 4) + 0.5, y: ((0.62 / 4) + 0.5) }, 
  { x: (1.18 / 4) + 0.5, y: ((-1.63 / 4) + 0.5) },
  { x: (-1.18 / 4) + 0.5,y: ((-1.63 / 4) + 0.5) },
  { x: (-1.91 / 4) + 0.5,y: ((0.62 / 4) + 0.5) }
];

I tried this:

const polygon = globalThis.add.polygon(worldPosX, worldPosY, pentagonVertices, 0x8d8d8d); 
var poly = globalThis.add.image(worldPosX, worldPosY, 'image', polygon);
globalThis.matter.add.gameObject(poly);
const polygon = globalThis.add.polygon(worldPosX, worldPosY, pentagonVertices, 0x8d8d8d); 
var poly =  globalThis.matter.add.gameObject(polygon); poly.setTexture('image')  //setTexture is not defined for some reason
globalThis.matter.add.gameObject(poly);

Solution

  • Well depends how you want to do it. There is an official examples showing this. It uses an atlas, but you can do it with an simple image, basically you need to use the Matter Sprite or Matter Image, and in the options you just need to apply the shape (link to the documentation).

       // for a simple hex you can use something like this.
       this.matter.add.image(x, y, 'image', null, {shape: {type: 'polygon', radius: 30, sides: 6 }});
       
       // form vertices something like this.
       this.matter.add.image(x, y, 'image', null,
            { shape: { type: 'fromVerts' , verts: [ 
                { x: 0, y: 0 },
                { x: 50, y: 0 },
                { x: 70, y: 25 },
                { x: 25, y: 50 },
                { x: -20, y: 25 },
            ]   
       }});