How to program a Box2D simple jump?

Hey there!

I'm very new to using libraries. My Processing journey began only a year ago. What I am trying to accomplish is to have my box jump if -- for instance -- the mouse is pressed. I believe this has something to with changing the linear velocity of the box? I've been trying to find a straightforward answer to this with no luck.

Here is my code so far. I also have some boundaries coded in, for the box to land on, but I omitted them here for simplicity's sake:

import shiffman.box2d.:
import org.jbox2d.collision.shapes.
;
import org.jbox2d.common.;
import org.jbox2d.dynamics.
;

Box2DProcessing box2d;

Box box;

void setup() {
size(500, 500);
box2d = new Box2DProcessing(this);
box2d.createWorld();
box2d.setGravity(0, -50);

box = new Box(width/4, height/2);
}
void draw() {
background(255);
box2d.step();
box.display();
}

class Box {
Body body;
float w;
float h;

Box(float x, float y) {
w = 12;
h = w;
makeBody(new Vec2(x, y), w, h);

}

void killBody() {
box2d.destroyBody(body);
}

boolean done() {
Vec2 pos = box2d.getBodyPixelCoord(body);
if (pos.y > height+w*h) {
killBody();
return true;
}
return false;
}
void display() {
Vec2 pos = box2d.getBodyPixelCoord(body);

rectMode(CENTER);
pushMatrix();
translate(pos.x, pos.y);
//rotate(-a);
fill(175);
stroke(0);
rect(0, 0, w, h);
popMatrix();
}

void makeBody(Vec2 center, float w_, float h_) {
PolygonShape sd = new PolygonShape();
float box2dW = box2d.scalarPixelsToWorld(w_/2);
float box2dH = box2d.scalarPixelsToWorld(h_/2);
sd.setAsBox(box2dW, box2dH);

FixtureDef fd = new FixtureDef();
fd.shape = sd;
fd.density = 0.5;
fd.friction = 0.003;
fd.restitution = 0.03;

BodyDef bd = new BodyDef();
bd.type = BodyType.DYNAMIC;
bd.position.set(box2d.coordPixelsToWorld(center));
body = box2d.createBody(bd);
body.createFixture(fd);
}
}

Again, I'm very new to this (the forum as well!) so any and all help is greatly appreciated!

Tagged:
Sign In or Register to comment.