I have now created a object in box2d and I am moving it using keyboard input. What I would like to do next is stop the vertical movement this body can have. In other words it should be able to move left and right, but not up and down, even when a collision with another object occurred.
My code for creating the box:
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);
Keyboard input:
$("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; }
}
});
and my update function, where the box named "player" in the bodies array is moved
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() );
}
So I want to prohibit all vertical movement that can occur on my bodies["player"] body, how would I do this.
I am now using a Prismatic joint, but there is a error when I try to make one of the bodies a static body:
var pj = new b2PrismaticJointDef();
pj.bodyA = bodies["left"];
pj.bodyB = bodies["player"];
pj.collideConnected = true;
prismaticJoint = world.CreateJoint(pj);
The creation of bodies["left"]:
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);