A quick start with nape and tilelayer  

  Haxe  nape  NME   Dec 26, 2012

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


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 :

haxelib install nape


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 :

haxelib install tilelayer

Simple implementation

So now to use these two great libraries :

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 :

class Main 
    var _space : Space;
    var _layer : TileLayer;
    var _entities : List<Entity>;

    public function new() 
        var tilesheet = new SparrowTilesheet(
        _layer = new TileLayer(tilesheet);

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

    public function update()
        for(entity in _entities)

Now to define a simple rectangular entity :

class Box extends Entity
    public function new(pSpace: Space)

        // 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 :

var box = new Box(_space);
_layer.addChild( box.sprite );

Share it