我正在使用 Node.js v0.10.35 并安装了调试模块(使用“npm install debug”)。以下是我用来测试在 Node.js 上运行的liquidfun.js 的“Hello LiquidFun”,改编自https://google.github.io/liquidfun/Programmers-Guide/html/md__chapter02__hello__box2_d.html
var lf=require('./liquidfun.js');
var debug=require('debug')('liquidfun');
var gravity = new lf.b2Vec2(0,-10);
var world = new lf.b2World(gravity);
lf.setWorld(world);
var groundBodyDef = new lf.b2BodyDef();
groundBodyDef.position.Set(0,-10);
var groundBody = world.CreateBody(groundBodyDef);
var groundBox = new lf.b2PolygonShape();
groundBox.SetAsBoxXY(50,10);
groundBody.CreateFixtureFromShape(groundBox,0);
var bodyDef = new lf.b2BodyDef();
bodyDef.type= lf.b2_dynamicBody;
bodyDef.position.Set(0,4);
var body=world.CreateBody(bodyDef);
var dynamicBox = new lf.b2PolygonShape;
dynamicBox.SetAsBoxXY(1,1);
fixtureDef = new lf.b2FixtureDef;
fixtureDef.shape = dynamicBox;
fixtureDef.density = 1;
fixtureDef.friction=0.3;
fixtureDef.restitution=0.5;
body.CreateFixtureFromDef(fixtureDef);
var timeStep=1/60;
var velocityIterations=6;
var positionIteration=2;
for (var i=0;i<60;i++)
{ world.Step(timeStep, velocityIterations, positionIteration);
var position = body.GetPosition();
var angle = body.GetAngle();
debug(position.x+" "+position.y+" "+angle);
}
为了使这项工作,将以下行添加到liquidfun.js(我使用的是v1.1.0)以将所有这些构造函数导出到上述程序:
module.exports = {
b2Vec2: b2Vec2,
b2BodyDef: b2BodyDef,
b2PolygonShape: b2PolygonShape,
b2FixtureDef: b2FixtureDef,
b2World: b2World,
b2_dynamicBody: b2_dynamicBody,
setWorld: function(_world){ world=_world; }
};
请注意,我已经定义了一个方法“setWorld(_world)”,用于将来自 nodejs 脚本的世界对象传递回该模块。原因是我发现liquidfun.js 需要定义变量“world”(这是一个 b2World 对象),而在我的示例中,我在模块外部创建了“world”,因此必须传回让它工作。或者,您可以在liquidfun.js 模块中创建“世界”并将其导出到nodejs 脚本。
顺便提醒一下,设置环境“DEBUG=liquidfun”查看模拟结果。在 Windows 上,键入以下内容以运行
set DEBUG=liquidfun & node hello_liquidfun.js