Skip to content

Instantly share code, notes, and snippets.

@restorer
Last active September 9, 2016 09:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save restorer/c160c1b844f4642c1bbd9e8c7aa2c89b to your computer and use it in GitHub Desktop.
Save restorer/c160c1b844f4642c1bbd9e8c7aa2c89b to your computer and use it in GitHub Desktop.
OpenFL 4 Tilemap visibility
package ;
import openfl.display.FPS;
import openfl.display.Sprite;
import openfl.display.Tile;
import openfl.display.Tilemap;
import openfl.display.Tileset;
import openfl.events.Event;
import openfl.events.MouseEvent;
import openfl.Assets;
import openfl.text.TextField;
class Bunny extends Tile {
public var speedX:Float;
public var speedY:Float;
public function new () {
super (0);
}
}
class Main extends Sprite {
private var bunnies:Array<Bunny>;
private var fps:FPS;
private var gravity:Float;
private var minX:Int;
private var minY:Int;
private var maxX:Int;
private var maxY:Int;
private var tilemap:Tilemap;
private var tileset:Tileset;
public function new () {
super ();
bunnies = new Array ();
minX = 0;
maxX = stage.stageWidth;
minY = 0;
maxY = stage.stageHeight;
gravity = 0.5;
var bitmapData = Assets.getBitmapData ("assets/wabbit_alpha.png");
tileset = new Tileset (bitmapData);
tileset.addRect (bitmapData.rect);
tilemap = new Tilemap (stage.stageWidth, stage.stageHeight, tileset);
addChild (tilemap);
fps = new FPS ();
addChild (fps);
var tf = new TextField();
tf.selectable = false;
tf.width = 300;
tf.height = 50;
tf.x = maxX - tf.width - 10;
tf.y = 10;
tf.text = "Click LMB to toggle first bunny visibility";
addChild(tf);
stage.addEventListener (MouseEvent.MOUSE_DOWN, stage_onMouseDown);
stage.addEventListener (Event.ENTER_FRAME, stage_onEnterFrame);
addBunny ();
addBunny ();
// bunnies[0].visible = false;
}
private function addBunny ():Void {
var bunny = new Bunny ();
bunny.x = 0;
bunny.y = 0;
bunny.speedX = Math.random () * 5;
bunny.speedY = (Math.random () * 5) - 2.5;
bunnies.push (bunny);
tilemap.addTile (bunny);
}
// Event Handlers
private function stage_onEnterFrame (event:Event):Void {
for (bunny in bunnies) {
bunny.x += bunny.speedX;
bunny.y += bunny.speedY;
bunny.speedY += gravity;
if (bunny.x > maxX) {
bunny.speedX *= -1;
bunny.x = maxX;
} else if (bunny.x < minX) {
bunny.speedX *= -1;
bunny.x = minX;
}
if (bunny.y > maxY) {
bunny.speedY *= -0.8;
bunny.y = maxY;
if (Math.random () > 0.5) {
bunny.speedY -= 3 + Math.random () * 4;
}
} else if (bunny.y < minY) {
bunny.speedY = 0;
bunny.y = minY;
}
}
}
private function stage_onMouseDown (event:MouseEvent):Void {
bunnies[0].visible = !bunnies[0].visible;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment