Reading OBJ files with quad faces into Phaser Mesh objects

A quick post about GameObjects.Mesh. As the documentation clearly states, this object only handles triangle faces. The Wavefront OBJ file format can handle more than 3 vertices for each face. Hence if you read create a Mesh like so:

this.load.obj('obj', '');
mesh = this.add.mesh(w/2, h/2).addVerticesFromObj('obj');

the below file from the example pages, you will get this:

With a very minor amendment, it is possible to read such files and create Mesh objects with complete set of triangle faces, to get this.

Reading of OBJ files relies on several methods including:

  • Phaser.Geom.Mesh.ParseObj - takes OBJ text file as input and outputs <Phaser.Types.Geom.Mesh.OBJData>
  • Phaser.Geom.Mesh.ParseObjMaterial
  • Phaser.Geom.Mesh.GenerateObjVerts - takes <Phaser.Types.Geom.Mesh.OBJData> as input and outputs <Phaser.Types.Geom.Mesh.GenerateVertsResult>

The first method actually reads all the vertices belonging to each face as defined by the OBJ file, but in the third method, only the first 3 vertices are read to create one face. ignoring the 4th vertex and beyond. All it takes is an addition of one additional for-loop, and amendment to 3 of the existing lines of code. Please play with the example below (heavily commented), which has links to lots of example OBJ files in the official Phaser github.

One side effect is that any OBJ files with “o” object groups will throw up an error (with the “native” Phaser methods, nothing is rendered). Nevertheless, you might find this small amendment useful if you know your model is good.