1. Home
  2. Docs
  3. In-game implementation
  4. Haxe in-game API
  5. Reading project JSON

Reading project JSON

Create the project class

Create a HX file for each LDtk project JSON. The filename isn’t important, pick whatever you like.

This HX will host all the the typed data extracted from the project file:

MyProject.hx:

private typedef _Tmp =
    haxe.macro.MacroType<[ ldtk.Project.build("path/to/myProject.ldtk") ]>;

Notes:

  • The “_Tmp” typedef isn’t actually directly used. But for syntax validity purpose, we need an identifier here. Anything will do the job.
  • This magic line will call the ldtk.Project.build macro which will parse the project JSON file, then use its content to dynamically construct types & classes definitions at compilation-time.

Create a project instance

Somewhere else, in your game code, add the following to instanciate the project data.

MyGame.hx:

class MyGame {
  public function new() {
    var p = new MyProject();
    trace( p.all_levels ); // Well done!
  }
}

Recommendations

1. Use a package

You should move the LDtk project class to a sub-package, to avoid class naming conflicts. To do so:

  1. move the MyProject.hx to a sub folder,
  2. add the corresponding package line at the beginning of this file (for example here: `assets`):
package assets; 

private typedef _Tmp =
     haxe.macro.MacroType<[ ldtk.Project.build("../path/to/myProject.json") ]>;

2. Use the import.hx file

For better code completion, it’s recommended to use the import.hx file (read more about it here):

  • Open or create the import.hx in the root of the source code folder,
  • Add the following line in it:
import MyProject;

This will allow easier access to all types defined by your project (enums, layers, entities etc.)

Accessing your project content

Layers, entities, fields etc.

The project content is easily accessed using various methods, as seen below:

var p = new MyProject();

// Access to a specific level
var level = p.all_levels.MyFirstLevel;
trace( level.pxWid );

// Access to a layer in this level
var someLayer = level.l_myIntGridLayer; // return a properly typed IntGrid layer
var entityLayer = level.l_myEntityLayer; // return a properly typed Entity layer

// Access to some entities in an Entity-layer
for( treasure in entityLayer.all_Treasure )
    trace( treasure.pixelX );

// Access to entity fields
var someTreasure = entityLayer.all_Treasure[0];
trace( someTreasure.f_isTreasureHidden ); // boolean custom field
trace( someTreasure.f_customColor_hex ); // color code in Hex format (#rrggbb)

Project types

If your project class is MyProject, you can access all its related types by using:

MyProject.Entity_Mob;
MyProject.Layer_MyIntGridLayer;
MyProject.Level;

This can be useful to hint function parameters:

function something( level : MyProject.Level ) {
  trace( level.identifier+" => "+level.pxWid+"px" );
}