Skip to content

Instantly share code, notes, and snippets.

@wwwins
Created June 4, 2012 04:09
Show Gist options
  • Save wwwins/2866276 to your computer and use it in GitHub Desktop.
Save wwwins/2866276 to your computer and use it in GitHub Desktop.
starling game class
package
{
import flash.display.Sprite;
import fr.kouma.starling.utils.Stats;
import nape.geom.Vec2;
import nape.phys.Body;
import nape.phys.BodyType;
import nape.phys.Material;
import nape.shape.Circle;
import nape.shape.Polygon;
import nape.space.Space;
import nape.util.BitmapDebug;
import nape.util.ShapeDebug;
import starling.core.Starling;
import starling.display.DisplayObject;
import starling.display.Image;
import starling.display.Sprite;
import starling.events.Event;
public class Game extends Sprite
{
[Embed(source = "assets/back.png")]
private var bg:Class;
private var space:Space;
private const DEBUG_ENABLE:Boolean = false;
//private var debug:BitmapDebug;
private var debug:ShapeDebug;
public function Game()
{
addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
// background image
addChild(Image.fromBitmap(new bg()));
// 設定場景 重力(影響掉落的速度)
space = new Space(new Vec2(0, 3000));
// 設置地板
var floor:Body = new Body(BodyType.STATIC);
floor.shapes.add(new Polygon(Polygon.rect(0, 600, 800, 20)));
floor.space = space;
// add starling stats
addChild(new Stats());
// debug
if (DEBUG_ENABLE) {
debug = new ShapeDebug(800, 600, 0x333333);
// faster render(but....need fucking adobe license)
//debug = new BitmapDebug(800, 600, 0x333333);
debug.draw(space);
// flash sprite
var _container_debug:flash.display.Sprite = new flash.display.Sprite();
// debug.display is a flash DisplayObject, it's not a starling Sprite.
_container_debug.addChild(debug.display);
Starling.current.nativeOverlay.addChild(_container_debug);
}
addEventListener(Event.ENTER_FRAME, loop);
}
private function loop(e:Event):void
{
if (DEBUG_ENABLE) {
debug.clear();
space.step(1 / 60);
debug.draw(space);
debug.flush()
}
else space.step(1 / 60);
if (Math.random() < 0.03)
addBall();
}
private function addBall():void
{
// 設定種類及座標
var ball:Body = new Body(BodyType.DYNAMIC, new Vec2(Math.random() * 750, 100));
// 設定球的規格及材質
ball.shapes.add(new Circle(51.5, null, new Material(20)));
// 預設提供幾種材質wood/steel/ice/rubber/glass/sand
//ball.shapes.add(new Circle(51.5, null, Material.rubber()));
ball.space = space;
// 貼上球的圖檔
if (!DEBUG_ENABLE) {
ball.graphic = new Basketball();
ball.graphicUpdate = updateGraphic;
addChild(ball.graphic);
}
}
private function updateGraphic(b:Body):void
{
// fixed memory leak
var gr:DisplayObject = b.graphic;
gr.x = b.position.x;
gr.y = b.position.y;
gr.rotation = b.rotation;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment