3

I'm trying to make a class that would draw objects of my JBox2d's world onto a canvas.

On update I have a call to

render.draw(canvas,world);

which passes the world and the canvas to the drawing class, which will be supposed to cycle through the world's objects and draw them into a canvas.

public void draw(Canvas canvas, World world)
{

    canvas.drawColor(0xFF6699FF);

    for ( Body b = world.getBodyList(); b!=null; b.getNext() )
    {
        Log.e("xy", String.valueOf( b.getPosition().x )+" "+String.valueOf( b.getPosition().y )  );
    }

}

yet it seems to go into an infinite loop, back button doesn't work, then it says "not responding" and offers to forceclose.

Any ideas what's the right way to cycle through the bodies in this case?

Thanks!

BeRecursive
  • 6,286
  • 1
  • 24
  • 41
Roger Travis
  • 8,402
  • 18
  • 67
  • 94

2 Answers2

6

As mentioned in my comment - the loop should be as follows:

for ( Body b = world.getBodyList(); b!=null; b = b.getNext() )
{
    Log.e("xy", String.valueOf(b.getPosition().x)+ " " + String.valueOf(b.getPosition().y));
}
BeRecursive
  • 6,286
  • 1
  • 24
  • 41
0

This is one way to do it. You get access to your different shapes (polygon / circle) through the world body list:

public void draw(Canvas canvas){
    Body body = world.getBodyList();
    while(body != null){
        Fixture fixture = body.getFixtureList();
        while(fixture != null){
            ShapeType type = fixture.getType();
            if(type == ShapeType.POLYGON){
                PolygonShape shape = (PolygonShape)fixture.getShape();
                // draw shape
            }else if(type == ShapeType.CIRCLE){
                CircleShape shape = (CircleShape)fixture.getShape();
                // draw shape
            }
            fixture = fixture.getNext();
        }
        body = body.getNext();
    }       
}
Jan-Terje Sørensen
  • 14,468
  • 8
  • 37
  • 37