Skip to content

Simple sprites

marcel euchner-martinez edited this page Jul 12, 2022 · 6 revisions

Creating simple sprites

Image resources

mysprite

mysprite_strip

mysprite_sheet

Code

import hxd.Res;

import h2d.Tile;
import h2d.Bitmap;

class SimpleSprites extends hxd.App {
    static function main() {
        new SimpleSprites();
        Res.initLocal();
    }

    override function init() {

        // creating a simple sprite
        var tile = Res.mysprite.toTile();
        var bmp  = new Bitmap( tile, s2d );
        infoLabel(bmp,"a simple sprite");

        // creating a sprite strip (a row of sprites, horizontal)
        var tiles = Res.mysprite_strip.toTile().split( 3 );
        var bmp   = new Bitmap( tiles[1], s2d );
        infoLabel(bmp,"from a strip\n(index = 1)");

        // creating a sprite sheet (a grid of sprites)
        var tiles = Res.mysprite_sheet.toTile().grid( 32 );
        var bmp   = new Bitmap( tiles[1][0], s2d );
        infoLabel(bmp,"from a sheet\n(index: x=1, y=0)");

        // using autoCut (will also punch the background in case it's not transparent)
        var tile = Tile.autoCut( Res.mysprite_sheet.toBitmap(), 32, 32 ); // (!!!) mind size (!!!)
        var bmp  = new Bitmap( tile.tiles[0][0], s2d );
        infoLabel(bmp,"autoCut()\nalso a sheet/grid\n(index: x=0, y=0)");

        // a simple sprite again, but the tile is centered and horizontally flipped
        var tile = tile.tiles[1][0]; // uses the sheet from above
        tile = tile.center();
        tile.flipX();
        var bmp  = new Bitmap( tile, s2d );
        infoLabel(bmp,"centered + flipped");

        // (representation)
        // position all added `h2d.Object`s
        var _y = 0;
        for( o in s2d.getLayer(0) )
            o.setPosition( 250, (++_y)*100 );
    }

    function infoLabel( obj:h2d.Object, infotext:String ){
        var t = new h2d.Text( hxd.res.DefaultFont.get(), obj );
        t.text = infotext;
        t.setPosition( -225, 0 );
    }
}

Directory setup

.
├── res/
│   └── mysprite.hx
│   └── mysprite_strip.hx
│   └── mysprite_sheet.hx
├── src/
│   └── SimpleSprites.hx
└── compile.hxml

hxml-file "compile.hxml"

-lib heaps
-lib hlsdl
-cp src
-p res
-main SimpleSprites
-hl simple_sprites_demo.hl

Clone this wiki locally