Box2dweb禁止移动

时间:2013-03-12 12:35:00

标签: javascript box2d box2dweb

我现在在box2d中创建了一个对象,我正在使用键盘输入来移动它。 我接下来要做的是停止这个身体可以有的垂直运动。换句话说,它应该能够向左和向右移动,但不能向上和向下移动,即使与另一个物体发生碰撞也是如此。

我创建框的代码:

           var fixDef2 = new b2FixtureDef;
           fixDef2.density = 1.0;
           fixDef2.friction = 0.5;
           fixDef2.restitution = 0.2;
           var bodyDef2 = new b2BodyDef;
           bodyDef2.type = b2Body.b2_dynamicBody;


           fixDef2.shape = new b2PolygonShape;
           fixDef2.shape.SetAsBox(
                 50/30 + 0.1 //half width
              ,  6/30 + 0.1 //half height
           );
        bodyDef2.position.x = Math.random() * 10;
        bodyDef2.position.y = Math.random() * 10;
        bodyDef2.fixedRotation = true;
bodies["player"]=world.CreateBody(bodyDef2);
bodies["player"].CreateFixture(fixDef2);
var direction = new b2Vec2(-100,0);

键盘输入:

        $("body").keydown(function (e) {
             switch(e.which){
                case 37:{ left = true; break;   }
                case 38:{ up=true; break; }
                case 39:{ right=true; break; }
                case 40:{ down = true; break; }                 
             }
        });
        $("body").keyup(function (e) {
             switch(e.which){
                case 37:{ left = false; break;  }
                case 38:{ up=false; break; }
                case 39:{ right=false; break; }
                case 40:{ down = false; break; }                    
             }
        });

和我的更新功能,其中移动了body数组中名为“player”的框

        if(left){
            var direction = new b2Vec2(-100,0);
            bodies["player"].ApplyForce( direction , bodies["player"].GetPosition() );
        }
        if(right){
            var direction = new b2Vec2(100,0);
            bodies["player"].ApplyForce( direction , bodies["player"].GetPosition() );
        }

所以我想禁止在我的身体[“玩家”身体上发生的所有垂直运动,我该怎么做。

我现在正在使用Prismatic关节,但是当我尝试使其中一个身体成为静态身体时出现错误:

var pj = new b2PrismaticJointDef();
pj.bodyA = bodies["left"];
pj.bodyB = bodies["player"];
pj.collideConnected = true;
prismaticJoint = world.CreateJoint(pj);

创建主体[“左”]:

     bodyDef.type = b2Body.b2_staticBody;
     fixDef.shape = new b2PolygonShape;
     fixDef.shape.SetAsBox(2, 14);
     bodyDef.position.Set(-1.8, 13);
     bodies["left"] = world.CreateBody(bodyDef).CreateFixture(fixDef);

1 个答案:

答案 0 :(得分:0)

使用b2_kinematicBody而不是b2_dynamicBody

类似的东西:

var con_body_def = new b2BodyDef;
con_body_def.type = b2Body.b2_kinematicBody;
con_body_def.position.y = con_bmp.y / SCALE;
con_body_def.position.x = con_bmp.x / SCALE;
var con_fix = new b2FixtureDef;
con_fix.restitution = SETTINGS.CON_E;
con_fix.friction = SETTINGS.CON_FR;
con_fix.shape = new b2PolygonShape;
    con_fix.shape.SetAsArray(get_shape());
con_fix.userData = 0;
var con_body = world.CreateBody(con_body_def);
con_body.CreateFixture(con_fix);

然后更新它的位置:

con_body.SetLinearVelocity(direction);

(看看game.js here是否有工作示例)