// A rectangular box class Box { Body body; // physics body FixtureDef fd; // physics fixture color c; float w,h; Box(float x, float y, float w_, float h_, int s) { w = w_; h = h_; // Build Body Definition BodyDef bd = new BodyDef(); if(s == 0){ bd.type = BodyType.DYNAMIC; bd.bullet = true; } else{ bd.type = BodyType.STATIC; } bd.position.set(box2d.coordPixelsToWorld(x,y)); // create the body body = box2d.createBody(bd); // Define a polygon (this is what we use for a rectangle) PolygonShape sd = new PolygonShape(); float box2dW = box2d.scalarPixelsToWorld(w/2); float box2dH = box2d.scalarPixelsToWorld(h/2); // Box2D considers the width and height of a sd.setAsBox(box2dW, box2dH); // rectangle to be the distance from the // center to the edge (so half of what we // normally think of as width or height.) // Define a fixture fd = new FixtureDef(); fd.shape = sd; // Parameters that affect physics if(s == 0){ fd.density = 1; fd.friction = 0.3; fd.restitution = 0.5; } // Attach Fixture to Body body.createFixture(fd); // assign a random color c = color(random(0,255),random(0,255),random(0,255)); } void display() { // We need the Body’s location and angle Vec2 pos = box2d.getBodyPixelCoord(body); float a = body.getAngle(); pushMatrix(); translate(pos.x,pos.y); // Using the Vec2 position and float angle to rotate(-a); // translate and rotate the rectangle fill(c); stroke(0); rectMode(CENTER); rect(0,0,w,h); popMatrix(); } float getX(){ // get the X position of the object Vec2 pos = box2d.getBodyPixelCoord(body); return pos.x; } float getY(){ // get the Y position of the object Vec2 pos = box2d.getBodyPixelCoord(body); return pos.y; } void setColor(color c_){ c = c_; } void setColor(int r, int g, int b){ c = color(r,g,b); } void applyImpulse(float x, float y){ Vec2 pos = box2d.getBodyPixelCoord(body); Vec2 v = new Vec2(x-pos.x, pos.y-y); body.applyLinearImpulse(v,body.getWorldCenter(),false); } void applyForce(float x, float y){ Vec2 v = new Vec2(x,y); body.applyForce(v,body.getWorldCenter()); } }