I have been recently trying to get back into LibGDX's version of Box2D, and I looked back at a demo I created a few months back, and my code looks fine, and from my Google search results, my code is fine, but for the life of me, I cannot get the Fixture to render.
Here is my (Minimalist example) code, and for the life of me, I cannot get it to work Note: I built a wrapper around the LibGDX Game class, should be self-explanatory:
public class TestBox2D extends EGGame {
int width;
int height;
static final Vector2 ZERO_GRAVITY = new Vector2(0f, 0f);
OrthographicCamera camera;
World world;
Body body;
Box2DDebugRenderer box2dDebugRenderer;
RayHandler rayHandler;
... // Removed Constructor, nothing special here.
#Override
protected void init() {
width = Gdx.graphics.getWidth() / 2;
height = Gdx.graphics.getHeight() / 2;
camera = new OrthographicCamera(width, height);
camera.position.set(width / 2, height / 2, 0);
camera.update();
world = new World(ZERO_GRAVITY, true);
box2dDebugRenderer = new Box2DDebugRenderer();
rayHandler = new RayHandler(world);
rayHandler.setCombinedMatrix(camera.combined);
// creating Body
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyDef.BodyType.StaticBody;
bodyDef.position.set(width/2, height/2);
body = world.createBody(bodyDef);
CircleShape shape = new CircleShape();
shape.setRadius(1f);
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = shape;
body.createFixture(fixtureDef);
}
#Override
protected void updateGame() {
world.step(1f / 30f, 6, 2);
rayHandler.update();
}
#Override
protected void renderGame() {
box2dDebugRenderer.render(world, camera.combined);
rayHandler.render();
}
#Override
public void dispose() {
world.dispose();
}
... // Removed main method, nothing special here.
}
Note that world.getBodyCount(); and world.getFixtureCount(); both return 1.
Probable causes of problem.
Check if you have called render on fixtures in either RayHandler class or Box2DDebugRenderer class.
You have not set the position of the circle shape. It might be lying on the edge and remain out of camera bounds.
Check your units. Radius of circle might be relatively so small that it would be invisible, or it might be so large that it might be covering entire screen.
Hope this helps.
You can try the following, one of the things mention Tanmay Patil, it resizes body:
Example:
Varible Class:
long time = 0;
float testSize = 0;
Call in your render method:
time += System.nanoTime();
if (time >= 100000000){
time = 0;
testSize += (0.1f);
body.getFixtureList().first().getShape().setRadius(testSize);
}
if not notice any change, try the opposite:
time += System.nanoTime();
if (time >= 100000000){
time = 0;
testSize -= (0.1f);
body.getFixtureList().first().getShape().setRadius(testSize);
}
Edit:
On the other hand, this does not affect the question, but you can call dispose here if you want:
.////////////
CircleShape shape = new CircleShape();
shape.setRadius(1f);
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = shape;
body.createFixture(fixtureDef);
shape.dispose();
}
Fixed.
The issue was that I was attempting to call RayHandler#render() after Box2DDebugRenderer.render(...) while the RayHandler didn't have any Light objects (Adding a PointLight allowed it to render), but whatever the reason for it is, it's weird, but calling the RayHandler#render() first allows it to work. This might be a bug in LibGDX that I will report.
Related
I'm trying to understand the amount of force i need to move my object. This is how my world is setup and the physics step is done
private void setupWorld() {
mWorld = new World(new Vector2(0f, -9.8f), true);
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyDef.BodyType.DynamicBody;
bodyDef.position.set(x, y);
body = world.createBody(bodyDef);
PolygonShape box=new PolygonShape();
box.setAsBox(1,1);
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = box;
fixtureDef.density = 1f;
fixtureDef.friction = 0.0f;
fixtureDef.restitution = 0.0f;
Fixture fixture = body.createFixture(fixtureDef);
box.dispose();
}
private void doPhysicsStep(float deltaTime) {
float frameTime = Math.min(deltaTime, 0.25f);
accumulator += frameTime;
while (accumulator >= TIME_STEP) {
body.applyForceToCenter(new Vector2(0, 10f), true);
world.step(TIME_STEP, VELOCITY_ITERATIONS, POSITION_ITERATIONS);
accumulator -= (TIME_STEP);
}
}
So i've got a 1x1 box with a density 1. Gravity is set at -9.8 and i'm expecting that when I apply an amount of force to my box that is greater than the gravity (in this example i've set it to 10) that the box should start moving up.
But the box doesn't move. I have to set the force to about 80 (i.e. body.applyForceToCenter(new Vector2(0, 80f), true);) before it starts to move the box.
I've considered that this is due to my time step (which i've currently set to 1/60f), but if anything taking that into account would reduce the force I'm applying in each step.
Can someone explain what i'm miscalculating here?
Your box has a mass of 4, not 1, because in method setAsBox(float hx, float hy) hx means half of desired width, and hy means half of desired height. So if you want to have a box 1 x 1 you will call setAsBox(0.5F, 0.5F).
But this doesn't explain why you need a force of 80 to move it, because force of 50 should be enough to make a difference.
Fg = m * g = 9.8 * 4 = 39.2
On my test project on object of mass 4 even the force of 40 is noticeable when applied programmatically (the delay of application start and pressing the button is significant so I avoid it).
I'm doing some initial experiments for a CS course, where I'm trying to use JBox2D as a physics library and drawing using JavaFX. I have had some luck draw circles that fall from the top of the screen, but now I have issues doing the same with rectangles (or any other shape).
I'm able to both draw and simulate, but I cannot figure out how to rotate the drawn nodes in JavaFX using values from the Body objects.
Here's my code for the bodies using JBox2D:
#Override
public Body createBody() {
BodyDef bd = new BodyDef();
bd.type = BodyType.DYNAMIC;
bd.position.set(centerX, centerY);
PolygonShape ps = new PolygonShape();
ps.setAsBox(2.0f,4.0f);
FixtureDef fd = new FixtureDef();
fd.shape = ps;
fd.density = 0.9f;
fd.friction = 0.3f;
fd.restitution = 0.5f;
Body b = PhysicalScene.world.createBody(bd);
b.createFixture(fd);
return b;
}
}
This is drawn using nodes in JavaFX - as written here:
#Override
public Node create() {
Rectangle r = new Rectangle();
r.setHeight(20);
r.setWidth(40);
r.setStroke(Color.RED);
r.setLayoutX(Physics.toPixelX(centerX));
r.setLayoutY(Physics.toPixelY(centerY));
// THIS IS WHAT I'M MISSING
// r.setRotate(/* some value from Body */);
return r;
}
The code isn't pretty, but I hope you get the idea. I am able to rotate the nodes by inserting arguments in the method, but do not know how to get these values from the Body objects themselves.
I hope you can help, thanks!
I am using Box2d for a game, and although I use large constants to set angular velocity, the fastest speed I can get is 1 revolution at 3.86 seconds.
I had checked my source code in the following thread and everything is the same with what I have been suggested from both users in here and in tutorials:
setAngularVelocity rotates really slowly
However than I noticed the following unresolved thread:
http://www.reddit.com/r/libgdx/comments/1qr2m3/the_strangest_libgdxbox2d_behaviour/
and noticed that might actually be the problem. Here is my dispose method
public void dispose() {
//Get Rid of Everything!
Assets.Clear();
GameEngine.Clear();
BallMap.clear();
PlayerMap.clear();
shapeRenderer.dispose();
debugRenderer.dispose();
world.dispose();
batch.dispose();
font.dispose();
}
They are all reinitialized on the beginning as follows:
this.game = game;
this.cameraWidth = cameraWidth*pixelRatio;
this.cameraHeight = cameraHeight*pixelRatio;
batch = new SpriteBatch();
shapeRenderer = new ShapeRenderer();
stateTime = 0F;
Scores = new Integer[]{0, 0};
debugRenderer = new Box2DDebugRenderer();
world = new World(new Vector2(0, 0), true); //Create a world with no gravity
GameEngine.setContactListener(world);
I navigate through screens with the following code:
public void create () {
scene_menu = new MainMenuScreen(this, cameraWidth, cameraHeight);
setScreen(scene_menu);
}
public void swtogame(){
scene_menu.dispose();
scene_game = new MatchScreen(this, cameraWidth, cameraHeight);
setScreen(scene_game);
}
public void swtomenu(){
scene_game.dispose();
scene_menu = new MainMenuScreen(this, cameraWidth, cameraHeight);
setScreen(scene_menu);
}
the way i initialize objects:
public Object(World world, short category, short mask, float x, float y, float radius, Sprite image,
float maxSpeed, float frictionStrength, float linearDamping, float angularDamping, boolean movable,
float elasticity, float mass){
this.world = world;
this.category = category;
this.mask = mask;
// We set our body type
this.bodyDef = new BodyDef();
if(movable==true){bodyDef.type = BodyType.DynamicBody;}else{bodyDef.type = BodyType.StaticBody;}
// Set body's starting position in the world
bodyDef.position.set(x, y);
bodyDef.linearDamping = linearDamping;
bodyDef.angularDamping = angularDamping;
// Create our body in the world using our body definition
this.body = world.createBody(bodyDef);
// Create a circle shape and set its radius
CircleShape circle = new CircleShape();
circle.setRadius(radius);
// Create a fixture definition to apply our shape to
fixtureDef = new FixtureDef();
fixtureDef.shape = circle;
fixtureDef.density = (float) (mass/(Math.PI*radius*radius));
fixtureDef.friction = frictionStrength;
fixtureDef.restitution = elasticity;
fixtureDef.filter.categoryBits = category;
fixtureDef.filter.maskBits = mask;
// Create our fixture and attach it to the body
this.fixture = body.createFixture(fixtureDef);
// BodyDef and FixtureDef don't need disposing, but shapes do.
circle.dispose();
... unrelated functions after that
}
Am I disposing correctly? Is this a bug? Is there any way to get around it and use the setAngularVelocity properly?
Because you haven't shown much code, I can I'm not 100% sure that I'm right, but I think that you are hitting the built in maximum movement limit of 2.0 units per time step. This means that at a typical framerate of 60Hz a body covering 2 units per timestep is moving at 120 m/s or 432 km/h (270 mph). Unfortunately it seems that there is no direct way to change this limit in Java, because this limit seems to be defined in the native C++ librarys.
But I think that the real problem is that you have a wrong scale. Box2D uses MKS (meters, kilograms, and seconds). And you may have used pixels instead of meters. The FAQ of Box2D suggests to use
objects [that are] between 0.1 - 10 meters
otherwise you can get strange situations.
See http://www.iforce2d.net/b2dtut/gotchas#speedlimit
and https://code.google.com/p/box2d/wiki/FAQ
I just found the problem, and it was pretty simple. Im just going to post this here for future googlers:
Object was actually rotating properly, the problem was in my drawing method, I didn't use conversion between radians to degrees in my batch.draw, and it interpreted everything in radians. I know such an amateur mistake! Thanks a lot for your time.
I want to know how to prevent an object in crossing another. I have a ball and a square which I can move whith my mouse. When my ball is on my square I move it (in top for example) if I go very slowly the ball remains on the square if not it crosses it.
if both of your 2 object have a fixture defined they will not be able to crossing one another this is an exmple of how a dynamic object who will be affected by physics in the BOX2D world must be created , and also this object can't tunneling through a sensor :
public Ball (World world){
this.world = world;
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyType.DYNAMIC;
bodyDef.position.set(0.0f/RATE, 0.0f/RATE);
Ballbody = world.createBody(bodyDef);
CircleShape circle = new CircleShape();
radius = (int) (Math.random()*30+15); // you can set a non randum raduis
circle.m_radius = radius/RATE;
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = circle;
fixtureDef.restitution = 0.8f;
fixtureDef.density = 2.0f;
fixtureDef.friction = 0.3f;
fixtureDef.filter.groupIndex = -1;
Ballbody.createFixture(fixtureDef);
Ballbody.getFixtureList().setUserData("Ballounaton"); // optional
Vec2 ballVec = new Vec2((float) (Math.random()*8+2),0.0f);
Ballbody.setLinearVelocity(ballVec);
}
make sure to define a fixture to your box2d dynamic or static object to avoid tunneling through a sensor like in this exmple :
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = circle;
fixtureDef.restitution = 0.8f;
fixtureDef.density = 2.0f;
fixtureDef.friction = 0.3f;
fixtureDef.filter.groupIndex = -1;
Ballbody.createFixture(fixtureDef);
according to BOX2D official documentation :
Recall that shapes don’t know about bodies and may be used
independently of the physics simulation. Therefore Box2D provides the
b2Fixture class to attach shapes to bodies. Fixtures hold the
following:
a single shape
broad-phase proxies
density, friction, and restitution
collision filtering flags
back pointer to the parent body
user data
sensor flag
So I'm trying to implement collision detection in my game and I have a layer in the tmx file called Collision. The LIBGDX onsite tutorials doesnt cover interaction with object layers and it was hard to figure out how to render the map in the first place. This is how I render my screen, I would like to learn how to get my collision layer and then get my sprite to interact with it.
#Override
public void render(float delta) {
translateCamera();
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
camera.update();
renderer.setView(camera);
renderer.render(bgLayers);
// renderer.render();
batch.begin();
batch.draw(playerDirect, Gdx.graphics.getWidth() / 2,
Gdx.graphics.getHeight() / 2);
batch.end();
renderer.render(fgLayers);
}
There is a way to use the object layer. Don't give up hope!
One major advantage of this method over using tile properties is the ease with which you can generate fewer, larger bodies for improved efficiency in Box2d. Plus, even better, those bodies can be any shape you want! Rather than dozens of squared-off bodies, my sample level in my game now has just three funny-shaped (read more organic-looking) ChainShape-based bodies.
I answered the same question on GameDev the other day, after a serious hunt deep in the jungles of the Web. The tutorial I found didn't quite work for me as-is, so a little editing later I came up with this:
public class MapBodyBuilder {
// The pixels per tile. If your tiles are 16x16, this is set to 16f
private static float ppt = 0;
public static Array<Body> buildShapes(Map map, float pixels, World world) {
ppt = pixels;
MapObjects objects = map.getLayers().get("Obstacles").getObjects();
Array<Body> bodies = new Array<Body>();
for(MapObject object : objects) {
if (object instanceof TextureMapObject) {
continue;
}
Shape shape;
if (object instanceof RectangleMapObject) {
shape = getRectangle((RectangleMapObject)object);
}
else if (object instanceof PolygonMapObject) {
shape = getPolygon((PolygonMapObject)object);
}
else if (object instanceof PolylineMapObject) {
shape = getPolyline((PolylineMapObject)object);
}
else if (object instanceof CircleMapObject) {
shape = getCircle((CircleMapObject)object);
}
else {
continue;
}
BodyDef bd = new BodyDef();
bd.type = BodyType.StaticBody;
Body body = world.createBody(bd);
body.createFixture(shape, 1);
bodies.add(body);
shape.dispose();
}
return bodies;
}
private static PolygonShape getRectangle(RectangleMapObject rectangleObject) {
Rectangle rectangle = rectangleObject.getRectangle();
PolygonShape polygon = new PolygonShape();
Vector2 size = new Vector2((rectangle.x + rectangle.width * 0.5f) / ppt,
(rectangle.y + rectangle.height * 0.5f ) / ppt);
polygon.setAsBox(rectangle.width * 0.5f / ppt,
rectangle.height * 0.5f / ppt,
size,
0.0f);
return polygon;
}
private static CircleShape getCircle(CircleMapObject circleObject) {
Circle circle = circleObject.getCircle();
CircleShape circleShape = new CircleShape();
circleShape.setRadius(circle.radius / ppt);
circleShape.setPosition(new Vector2(circle.x / ppt, circle.y / ppt));
return circleShape;
}
private static PolygonShape getPolygon(PolygonMapObject polygonObject) {
PolygonShape polygon = new PolygonShape();
float[] vertices = polygonObject.getPolygon().getTransformedVertices();
float[] worldVertices = new float[vertices.length];
for (int i = 0; i < vertices.length; ++i) {
worldVertices[i] = vertices[i] / ppt;
}
polygon.set(worldVertices);
return polygon;
}
private static ChainShape getPolyline(PolylineMapObject polylineObject) {
float[] vertices = polylineObject.getPolyline().getTransformedVertices();
Vector2[] worldVertices = new Vector2[vertices.length / 2];
for (int i = 0; i < vertices.length / 2; ++i) {
worldVertices[i] = new Vector2();
worldVertices[i].x = vertices[i * 2] / ppt;
worldVertices[i].y = vertices[i * 2 + 1] / ppt;
}
ChainShape chain = new ChainShape();
chain.createChain(worldVertices);
return chain;
}
}
Assuming you've set things up so that the size of your tiles correspond to 1 square metre (1 square unit, if you prefer) in your Box2d World, the static Bodys this produces will be exactly where you drew them in Tiled. It was so satisfying to see this up and running, believe you me.
I'd reccomend adding blocked properties to the actual tiles themselves - you can add tile properties via the Tiled editor on the actual tileset. You can retrieve their properties on the tileset. I'm going to quote the documentation:
A TiledMap contains one or more TiledMapTileSet instances. A tile
set contains a number of TiledMapTile instances. There are multiple
implementations of tiles, e.g. static tiles, animated tiles etc. You
can also create your own implementation for special
Cells in a tile layer reference these tiles. Cells within a layer can
reference tiles of multiple tile sets. It is however recommended to
stick to a single tile set per layer to reduce texture switches.
Specifically, call getProperties on the tile in a tileset. This will retrieve the propeties - then you can compare to your custom attribute and this can tell you if a particular tile is blocked - then you can go ahead and implement your own collision logic.