haxe的nem与box2d入门例子在物体下贴图

haxe的nem与box2d入门例子在物体上贴图
接上篇的例子:haxe的nem与box2d入门例子
这个例子是将一个png的图片贴到小球上,并与小球一起做*落体运动。
haxe的nem与box2d入门例子在物体下贴图
首先导入3个类包:
import nme.display.BitmapData;
import nme.display.Bitmap;
import nme.Assets;


首先创建一个Circle类:
/**
 * 球体
 */
class Circle extends Sprite {
    private var radius : Float;
    private var wheel : Bitmap;
    
    public function new(x : Float, y : Float, radius : Float) {
        super();
        
        this.radius = radius;    
        this.wheel = new Bitmap(Assets.getBitmapData('img/wheel.png'));
        this.wheel.x = x - radius;
        this.wheel.y = y - radius;
        
        this.addChild(this.wheel);
    }
    
    public function move(position : B2Vec2) : Void {
        //box2d以物体的中心为原点,而nme则以左上角为原点,所有要减去圆的半径
        this.wheel.x = position.x / Settings.METERTOPIXEL - this.radius;
        this.wheel.y = position.y / Settings.METERTOPIXEL - this.radius;
    }
}


然后在createBall方法中加入:
    //添加皮肤
    var myCircle : Circle = new Circle(x, y, radius);
    wheelBodyDef.userData = myCircle;
    addChild(myCircle);


上面的代码要放在var wheelBody : B2Body = world.createBody(wheelBodyDef);之前。

按F5调试你会只会看到一个球体,这个球体*落体后你就可以看到刚才加载的那张图片。
下面设置球体与皮肤的同步运动:
在update方法中加入同步更新位置:
    var body : B2Body = world.getBodyList();        
    while (null != body) {
        //body.m_type == 2时,物体为动态的
        if (2 == body.m_type && Std.is(body.getUserData(), Sprite)) {
            body.getUserData().move(body.getPosition());
        }
        body = body.getNext();
    }


在init方法中把drawDebug()及update()方法中的world.drawDebugData();调用去掉,按F5,加载在图片在做*落体运动。

最后给出这个例子的下载地址:
最后给出这个例子的下载地址:
    共享链接:http://163.fm/TygF3Ie

    提取码:1x1cZAxs

原文地址:http://gentwolf.sinaapp.com/index/detail/170.html