Collision problem JBox2D

I work with Processing and the JBox2D library and wanna code a new Ping Pong game. But if I move the player to the top border (or lower border), he collide on a wrong position.

The picture shows player 1 colliding with the top border.

If I move the player again upwards then he moves through the border.

My Player Class:

class Player {
Body body;
float pWidth;
float pHeight;
Vec2 pos;
float speed;

Player(float x, float y, float w, float h) {
pWidth = w;
pHeight = h;
speed = 5;
pos = new Vec2(0, 0);

// Add the player to the box2d world
makeBody(new Vec2(x, y), w, h);
}

void playerStep(){
pos = box2d.getBodyPixelCoord(body);
}

void moveUp() {
body.setTransform(box2d.coordPixelsToWorld(pos.x, pos.y-speed),0);
}

void moveDown() {
body.setTransform(box2d.coordPixelsToWorld(pos.x, pos.y+speed),0);
}

void makeBody(Vec2 center, float w_, float h_) {

// Define the body and make it from the shape.
BodyDef bd = new BodyDef();
bd.type = BodyType.DYNAMIC;
bd.position.set(box2d.coordPixelsToWorld(center));

PolygonShape sd = new PolygonShape();
sd.setAsBox(box2d.scalarPixelsToWorld(w_), box2d.scalarPixelsToWorld(h_));

// Define a fixture.
FixtureDef fd = new FixtureDef();
fd.shape = sd;

// Parameters that affect physics.
fd.density = 5;
fd.friction = 2;
fd.restitution = 1;

body = box2d.createBody(bd);
body.createFixture(fd);
}
}


Boundary Class:

class Boundary {

// A boundary is a simple rectangle with x,y,width,and height.
float x;
float y;
float w;
float h;

// But we also have to make a body for box2d to know about it.
Body b;

Boundary(float x_, float y_, float w_, float h_) {
x = x_;
y = y_;
w = w_;
h = h_;

// Define the polygon.
PolygonShape sd = new PolygonShape();

// Figure out the box2d coordinates.
float box2dW = box2d.scalarPixelsToWorld(w/2);
float box2dH = box2d.scalarPixelsToWorld(h/2);

// We're just a box.
sd.setAsBox(box2dW, box2dH);

// Create the body.
BodyDef bd = new BodyDef();
bd.type = BodyType.STATIC;
bd.position.set(box2d.coordPixelsToWorld(x, y));
b = box2d.createBody(bd);
b.createFixture(sd, 1);
}

void display() {
fill(255);
rectMode(CENTER);
rect(x, y, w, h);
}
}

• I'm not familiar with box2d, however, just from eyeballing it the problem seems to be because you are directly modifying the position of the rectangle, possibly bypassing the collision testing. Could easily be wrong. – newton1212 Jun 11 '15 at 13:10
• @newton1212 is right. When you alter the entity's position, you are bypassing the collision checks that would normally be done with your physics engine. You need to modify the velocity instead of the position, in order to move your entity properly inside of your simulated world. – jgallant Jun 11 '15 at 16:16