I am trying to make ball bouncing between 4 walls using the JBox2D library in Java. The code above is the code I use to create and the ball in the world.
// Creating the Body Definition
BodyDef bodyDef = new BodyDef();
// Set position to Body Definition
bodyDef.position.set(x, y);
// Setting body type to body definition
bodyDef.type = bodyType;
// Creating CircleShape object
CircleShape circleShape = new CircleShape();
// Setting radius to CircleShape
circleShape.m_radius = radius;
/ /Creating Fixture Definition object
FixtureDef fixtureDef = new FixtureDef();
// Setting circleShape as shape of fixture definition
fixtureDef.shape = circleShape;
// This defines the heaviness of the body with respect to its area
fixtureDef.density = density;
// This defines how bodies slide when they come in contact with each other.
// Friction value can be set between 0 and 1. Lower value means more slippery bodies.
fixtureDef.friction = friction;
// This define how bouncy is the body.
// Restitution values can be set between 0 and 1.
// Here higher value means more bouncy body.
fixtureDef.restitution = restitution;
// "Uploading" the ball into the world
Body body = world.createBody(bodyDef);
// Setting fixtureDef as body's fixture
body.createFixture(fixtureDef);
And this is the code I used to make a wall. For example the right wall.
// Creating the Body Definition
BodyDef bodyDef = new BodyDef();
// Set position to Body Definition
bodyDef.position.set(850f, 0f);
// Setting body type as static
bodyDef.type = BodyType.STATIC;
// Creating CircleShape object
PolygonShape polygonShape = new PolygonShape();
// Set polygon shape as a box
polygonShape.setAsBox(1f - 44,1000);
// Creating Fixture Definition object
FixtureDef fixtureDef = new FixtureDef();
// Setting circleShape as shape of fixture definition
fixtureDef.shape = polygonShape;
fixtureDef.friction = 0f;
// "Uploading" the ball into the world
Body body = world.createBody(bodyDef);
// Setting fixtureDef as body's fixture
body.createFixture(fixtureDef);
The ball starts to move vertically or horizontally when it collides with another body. The circle goes fine until it collides with another body. As some other posts said, I tried setting the ball's friction to 0 but that didn't work for me. These are the values I use for the ball:
tileFixture.density = 1f;
tileFixture.friction = 1f;
tileFixture.restitution = 10000f;
I found my mistake. The problem is in the value of the restitution. The value is a lot so JBox2D makes move horizontally or vertically. I changed the value of restitution to 1f and now it works great.