だから私は長方形のボディボディを持っています。半分の幅と半分の高さを取得するにはどうすればよいですか?(他に答えが見つかりませんでした)
1 に答える
1
残念ながら、Box2D(したがってJBox2D)には長方形自体の概念がないため、完全に単純ではありません。長方形はでありPolygonShape
、その形状はおそらく。を使用して指定されてsetAsBox(halfWidth, halfHeight)
います。
それを取得しhalfWidth
、halfHeight
を作成した後Fixture
、次のことを考慮してください(必要に応じてリファクタリングしてください)。
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です
お役に立てば幸いです。
PolygonShape
同様の注意点として、 :の寸法を取得する簡単な方法を次に示します。
public static Vec2 getDimensions( final PolygonShape shape ) {
float minX = Float.MAX_VALUE;
float maxX = Float.MIN_VALUE;
float minY = Float.MAX_VALUE;
float maxY = Float.MIN_VALUE;
final int vertices = shape.getVertexCount();
for( int i = 0; i < vertices; i++ ) {
final Vec2 v = shape.getVertex( i );
minX = (v.x < minX) ? v.x : minX;
maxX = (v.x > maxX) ? v.x : maxX;
minY = (v.y < minY) ? v.y : minY;
maxY = (v.y > maxY) ? v.y : maxY;
}
return new Vec2( maxX - minX, maxY - minY );
}
Vec2
返されたディメンションを半分に分割すると、目的の値も取得されます。
于 2012-12-20T20:28:40.403 に答える