如何在jbox2d中获取身体的半宽和半高

时间:2012-08-24 13:38:49

标签: java entity rectangles jbox2d

所以我的Body body是一个矩形。我如何得到它的半宽和半高?(我在其他地方找不到答案)

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

不幸的是,它并非完全直截了当,因为Box2D(因此JBox2D)本身没有任何矩形概念。矩形是PolygonShape,其形状可能是使用setAsBox(halfWidth, halfHeight)指定的。

无论如何,在创建halfWidth之后,我们如何得到halfHeightFixture

请不要复制&粘贴此代码;根据您的应用需要对其进行重构。

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&amp; 2.5

     

多边形具有半宽和宽度。身高:137.0&amp; 42.0

     

圆的半径为:20.0

希望有所帮助。