xxxxxxxxxx
70
class Box{
constructor(pos,rect,type){
this.pos = pos;
this.rect = rect;
this.type = type;
//step 1 define body
let bd = new box2d.b2BodyDef();
if(this.type=="dynamic"){//b2_staticBody
bd.type = box2d.b2BodyType.b2_dynamicBody;
}else if(this.type=="static"){
bd.type = box2d.b2BodyType.b2_staticBody;
}
bd.position = scaleToWorld(this.pos.x,this.pos.y);
//step 2 create body
this.body = world.CreateBody(bd);
//step 3 create shape
let ps = new box2d.b2PolygonShape();
ps.SetAsBox(scaleToWorld(this.rect/2),scaleToWorld(this.rect/2));
//step 4 create fixture
let fd = new box2d.b2FixtureDef();
fd.density = 19.35;
fd.friction = 2.3;
fd.restitution = 0.2;
//step 5 attach shape to body
fd.shape = ps;
this.body.CreateFixture(fd);
//some additional stuff
if(this.type == "dynamic"){
this.body.SetLinearVelocity(new box2d.b2Vec2(0, 9.807));//gravity
}
//this.body.SetAngularVelocity(random(-5, 5));//rotation
}
applyForce(){
let pos = box2d.b2Vec2(0,0);
this.body.applyForce(pos,new box2d.b2Vec2(200,0));
}
display(){
let pos = scaleToPixels(this.body.GetPosition());
let a = this.body.GetAngleRadians();
noStroke()
rectMode(CENTER);
push();
translate(pos.x,pos.y);
rotate(a);
fill("grey");
rect(0,0,this.rect,this.rect);
pop();
}
}