Box2D机身在碰撞时不会旋转

时间:2011-07-22 23:45:50

标签: javascript canvas physics box2d

我一直试图进入Box2DWeb这是Box2D的AS端口的JS端口。只是尝试进行简单的设置,其中有一个静态斜坡和一个动态框。这是我的代码:

var b2World =  Box2D.Dynamics.b2World;
var b2DebugDraw = Box2D.Dynamics.b2DebugDraw;
var b2Vec2 = Box2D.Common.Math.b2Vec2;
var b2BodyDef = Box2D.Dynamics.b2BodyDef;
var b2Body = Box2D.Dynamics.b2Body;
var b2FixtureDef = Box2D.Dynamics.b2FixtureDef;
var b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape;
var b2CircleShape = Box2D.Collision.Shapes.b2CircleShape;

var width = 8;
var height = 4;

var world = new b2World(new b2Vec2(0, 10), true);

var debugDraw = new b2DebugDraw();
debugDraw.SetSprite(document.getElementById("canvas").getContext("2d"));
debugDraw.SetDrawScale(100); //Arena is 8 meters by 4 meters
debugDraw.SetFillAlpha(0.5);
debugDraw.SetLineThickness(1);
debugDraw.SetFlags(b2DebugDraw.e_shapeBit);
world.SetDebugDraw(debugDraw);

var bodyDef = new b2BodyDef();
bodyDef.type = b2Body.b2_staticBody;
bodyDef.position.Set(3.5, 3)
var body = world.CreateBody(bodyDef);
body.SetAngle(Math.PI / 4);
var shape = new b2PolygonShape();
shape.SetAsBox(1, 0.25);
var fixtureDef = new b2FixtureDef();
fixtureDef.shape = shape;
fixtureDef.density = 1;
fixtureDef.friction = 0.3;
body.CreateFixture(fixtureDef);

var bodyDef = new b2BodyDef();
bodyDef.type = b2Body.b2_dynamicBody;
bodyDef.position.Set(3.5, 1)
var body = world.CreateBody(bodyDef);
var shape = new b2PolygonShape();
shape.SetAsBox(0.10, 0.10);
var fixtureDef = new b2FixtureDef();
fixtureDef.shape = shape;
body.CreateFixture(fixtureDef); 

setInterval(function() {
    world.Step(1 / 60, 10, 10);
    world.DrawDebugData();
    world.ClearForces();
    console.log(body.GetAngle());
}, 1000 / 60);

您可以看到实时结果on jsFiddle。如您所见,当盒子撞到斜坡时,盒子不会旋转。我做错了什么?

感谢。

一些资源:

2 个答案:

答案 0 :(得分:14)

为盒子添加摩擦力和密度。 ...并且不要立即离开irc通道,有时需要超过3分钟。

答案 1 :(得分:5)

啊,你必须设置摩擦力&坠落物体的夹具上的密度,而不是身体。

var fixtureDef = new b2FixtureDef();
fixtureDef.shape = shape;
fixtureDef.friction = 0.3
fixtureDef.density = 1   
body.CreateFixture(fixtureDef);

顺便说一句,感谢我指向Box2D的方向 - 之前我没见过那个物理引擎,看起来很有趣:)