Skip to content

Instantly share code, notes, and snippets.

@darkwave
Created September 26, 2013 20:40
Show Gist options
  • Save darkwave/6720206 to your computer and use it in GitHub Desktop.
Save darkwave/6720206 to your computer and use it in GitHub Desktop.
A simple top-view car movement and collisions using Box2D. You need PBox2D by Daniel Shieffman in order to run this application. You'll need also 3 images for the sprites.
// A rectangular box
class Box {
// Instead of any of the usual variables, we will store a reference to a Box2D Body
Body body;
float w,h;
Box(float x, float y) {
this(x, y, 64, 64, false);
}
Box(float x, float y, int _w, int _h, boolean kinematic) {
w = _w;
h = _h;
// Build Body
BodyDef bd = new BodyDef();
if (kinematic)
bd.type = BodyType.KINEMATIC;
else
bd.type = BodyType.DYNAMIC;
bd.position.set(box2d.coordPixelsToWorld(x,y));
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
FixtureDef fd = new FixtureDef();
fd.shape = sd;
// Parameters that affect physics
fd.density = 1;
fd.friction = 0.5;
fd.restitution = 0.3;
// Attach Fixture to Body
body.createFixture(fd);
}
PVector getBodyPixelCoord() {
Vec2 pos = box2d.getBodyPixelCoord(body);
return new PVector(pos.x, pos.y);
}
void update() {
Vec2 currentVelocity = body.getLinearVelocity();
currentVelocity.x *= 0.9;currentVelocity.y *= 0.9;
body.setLinearVelocity(currentVelocity);
}
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(175);
//stroke(0);
displayImpl();
popMatrix();
}
void displayImpl() {
beginShape();
scale(w * .5, h * .5);
texture(crateSprite);
textureMode(NORMAL);
vertex(-1, -1, 0, 0);
vertex(1, -1, 1, 0);
vertex(1, 1, 1, 1);
vertex(-1, 1, 0, 1);
endShape();
}
}
class Car extends Box {
Car(float x, float y) {
super(x, y, carSprite.width, carSprite.height, false);
body.setTransform(new Vec2(0, 0), 0);
}
void displayImpl() {
imageMode(CENTER);
image(carSprite, 0, 0);
}
void update() {
if (accelerate)
velocity += 2;
float increment = 5 * velocity * .01;
if (turnRight)
angle -= increment;
if (turnLeft)
angle += increment;
velocity *= .95;
body.setTransform(body.getPosition(), radians(angle));
PVector direction = PVector.fromAngle(radians(angle));
direction.mult(velocity);
direction.limit(20);
body.setLinearVelocity(new Vec2(direction.x, direction.y));
}
}
import pbox2d.*;
import org.jbox2d.collision.shapes.*;
import org.jbox2d.common.*;
import org.jbox2d.dynamics.*;
// A list for all of our crates
ArrayList<Box> boxes;
//player car
Car car;
float angle = 0;
float velocity = 0;
boolean accelerate, turnRight, turnLeft;
PBox2D box2d; //physics by Box2D!
//random car, crates and street textures/sprites
PImage carSprite, crateSprite, asfaltTexture;
void setup() {
size(displayWidth, displayHeight, P3D);
noStroke();
//you must add the following files into your "data/" folder
carSprite = loadImage("car.png");
crateSprite = loadImage("crate.jpg");
asfaltTexture = loadImage("asfalt.jpg");
// Initialize and create the Box2D world
box2d = new PBox2D(this);
box2d.createWorld();
box2d.setGravity(0.0, 0.0);
// Create ArrayLists
boxes = new ArrayList<Box>();
car = new Car(0, 0);
}
void draw() {
background(#333333);
car.update();
for (Box b: boxes) {
b.update();
}
// We must always step through time!
box2d.step();
PVector playerPosition = car.getBodyPixelCoord();
// When the mouse is clicked, add a new Box object
if (mousePressed) {
Box p = new Box(playerPosition.x + (width / 2) - mouseX, playerPosition.y + (height / 2) - mouseY);
println((playerPosition.x - (width / 2)) + "," + (playerPosition.y + mouseY - (height / 2)));
boxes.add(p);
}
ortho();
camera(playerPosition.x, playerPosition.y, 500, playerPosition.x, playerPosition.y, 0, 0, -1, 0);
pushMatrix();
beginShape();
scale(1024, 1024);
texture(asfaltTexture);
textureMode(NORMAL);
vertex(-1, -1, 0, 0);
vertex(1, -1, 1, 0);
vertex(1, 1, 1, 1);
vertex(-1, 1, 0, 1);
endShape();
popMatrix();
fill(255, 0, 0);
car.display();
fill(128);
// Display all the boxes
for (Box b: boxes) {
b.display();
}
}
void keyPressed() {
if (keyCode == LEFT) {
turnLeft = true;
//car.body.setTransform(car.body.getPosition().sub( new Vec2(2, 0)), radians(car.body.getAngle() + 5));
}
else if (keyCode == RIGHT) {
turnRight = true;
}
if (keyCode == UP)
accelerate = true;
}
void keyReleased() {
if (keyCode == UP) {
accelerate = false;
}
if (keyCode == LEFT) {
turnLeft = false;
}
if (keyCode == RIGHT) {
turnRight = false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment