A quick start with nape and tilelayer

Recently, I started a mobile game with NME, and I wanted to give a try to nape. Since I’ve seen the NME’s runnermark, I’ve wanted to try the tilelayer library too. So why not dot it at the same time !

Overall view

Nape

This month was annonced the 2.0 version of nape. Nape is an open-source Haxe/AS3 physics engine that lets you do cross platform applications. It’s fast and powerful (actually I prefer nape over box2d, it’s much easier to use, and really fast). See by yourself : http://napephys.com/samples.html.

Just download it through haxelib :

1
haxelib install nape

Tilelayer

To quote the github description :

A lightweight and very optimized wrapper over NME’s powerful but lowlevel ‘drawTiles’ which offers the best rendering performance (ie. batching) on native platforms.

To install the haxelib version :

1
haxelib install tilelayer

Simple implementation

So now to use these two great libraries :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import nape.phys.Body;
import aze.display.TileSprite;

class Entity
{
    // The tilelayer's sprite
    public var sprite(default, null): TileSprite;
    // The nape's body
    public var body(default, null) : Body;

    public function new(){}
	
    /**
     * Update the positions and the rotation
     **/
    public function update()
    {
        if(sprite != null && body != null)
        {
            sprite.x = body.position.x;
            sprite.y = body.position.y;
            sprite.rotation = body.rotation;
        }
    }
}

All the entities will have to be updated on each frame, as well as the nape’s space and the layer :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Main 
{
    var _space : Space;
    var _layer : TileLayer;
    var _entities : List<Entity>;

    public function new() 
    {
        var tilesheet = new SparrowTilesheet(
            Assets.getBitmapData("assets/spritesheet.png"), 
            Assets.getText("assets/spritesheet.xml")
        );
        _layer = new TileLayer(tilesheet);
        addChild(_layer.view);

        _space = new Space( new Vec2(0, 600));
    }

    public function update()
    {
        _space.step(1/60);
        for(entity in _entities)
            entity.update();
        _layer.render();
    }
}

Now to define a simple rectangular entity :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Box extends Entity
{
    public function new(pSpace: Space)
    {
        super();

        // Nape's data
        body = new Body(BodyType.DYNAMIC);
        body.shapes.add(new Polygon(Polygon.box(50, 50)));
        body.position.setxy(10, 10);
        body.space = pSpace;
        
        sprite = new TileSprite('box');
    }
}

And simply add it to the stage :

1
2
3
var box = new Box(_space);
_entities.add(box);
_layer.addChild( box.sprite );