2012-08-24 54 views

回答

0

不幸的是,它不是Box2D(因此JBox2D)本身沒有任何矩形概念。該矩形是PolygonShape,其形狀可能是使用setAsBox(halfWidth, halfHeight)指定的。

無論如何,在創建Fixture之後,我們如何得到halfWidthhalfHeight

請不要複製&粘貼此代碼;按照您的應用程序需要重構它。

public void checkOutThisFixture(Fixture fixture) { 
    Shape fixtureShape = fixture.getShape(); 
    if (fixtureShape instanceof PolygonShape) { 
     PolygonShape polygonShape = (PolygonShape) fixtureShape; 
     Float minX = null; 
     Float maxX = null; 
     Float minY = null; 
     Float maxY = null; 
     for (int i = 0; i < polygonShape.getVertexCount(); i++) { 
      Vec2 nextVertex = polygonShape.getVertex(i); 
      float x = nextVertex.x; 
      float y = nextVertex.y; 
      if (minX == null || x < minX) { 
       minX = x; 
      } 
      if (maxX == null || x > maxX) { 
       maxX = x; 
      } 
      if (minY == null || y < minY) { 
       minY = y; 
      } 
      if (maxY == null || y > maxY) { 
       maxY = y; 
      } 
     } 
     float width = maxX - minX; 
     float height = maxY - minY; 
     float halfWidth = width/2; 
     float halfHeight = height/2; 
     System.out.println("The polygon has half width & height of: " + halfWidth + " & " + halfHeight); 
    } else if (fixtureShape instanceof CircleShape) { 
     float radius = ((CircleShape) fixtureShape).m_radius; 
     System.out.println("The circle has a radius of : " + radius); 
    } else { 
     // TODO handle other shapes 
    } 
} 

而且,你的問題專門詢問從Body得到這個信息。在這裏你去:

public void checkOutTheseFixtures(Body body) { 
    for (Fixture fixture = body.getFixtureList(); fixture != null; fixture = fixture.getNext()) { 
     checkOutThisFixture(fixture); 
    } 
} 

和幾個測試:

World world = new World(new Vec2(0, 0), true); 
Body body = world.createBody(new BodyDef()); 

// Add a circle 
CircleShape circle = new CircleShape(); 
circle.m_radius = 20; 
body.createFixture(circle, 5); 

// Add a box 
PolygonShape rectangle = new PolygonShape(); 
rectangle.setAsBox(137, 42); 
body.createFixture(rectangle, 10); 

// Add a more complex polygon 
PolygonShape polygon = new PolygonShape(); 
Vec2[] vertices = new Vec2[5]; 
vertices[0] = new Vec2(-1, 2); 
vertices[1] = new Vec2(-1, 0); 
vertices[2] = new Vec2(0, -3); 
vertices[3] = new Vec2(1, 0); 
vertices[4] = new Vec2(1, 1); 
polygon.set(vertices, 5); 
body.createFixture(polygon, 10); 

checkOutTheseFixtures(body); 

打印:

多邊形具有半寬&高度:1.0 & 2.5

多邊形有半身寬度&身高:137.0 & 42.0

圓的面積半徑:20.0

希望有所幫助。