Example usage for com.badlogic.gdx.physics.box2d PolygonShape set

List of usage examples for com.badlogic.gdx.physics.box2d PolygonShape set

Introduction

In this page you can find the example usage for com.badlogic.gdx.physics.box2d PolygonShape set.

Prototype

public void set(float[] vertices) 

Source Link

Document

Copy vertices from the given float array.

Usage

From source file:Tabox2D.java

License:Open Source License

private Tabody generateRegularPoly(String name, String type, float x, float y, float rad) {
    // Scale proportions:
    x /= meterSize;//  ww w.  j  a  va2 s  .co m
    y /= meterSize;
    rad /= meterSize;

    PolygonShape polygonShape;
    BodyDef defPoly = new BodyDef();

    setType(defPoly, type);

    // Generate points:
    List<Vector2> pts = new ArrayList<Vector2>();
    Vector2 p0 = new Vector2(0, rad);

    float conv = MathUtils.degreesToRadians;
    float angleInDeg = polyInfo.get(name + "_angle");
    float cos = MathUtils.cos(conv * angleInDeg);
    float sin = MathUtils.sin(conv * angleInDeg);

    for (int i = 0; i < polyInfo.get(name); i++) {
        pts.add(new Vector2(p0.x, p0.y));
        p0.set(p0.x, p0.y);

        float newX = p0.x * cos - p0.y * sin;
        float newY = p0.x * sin + p0.y * cos;

        p0.x = newX;
        p0.y = newY;
    }

    // Get bounding box:

    float[] rawPoints = new float[pts.size() * 2];
    int pointIndex = 0;
    for (int i = 0; i < rawPoints.length - 1; i += 2) {
        rawPoints[i] = pts.get(pointIndex).x;
        rawPoints[i + 1] = pts.get(pointIndex).y;
        pointIndex++;
    }

    Polygon polyForBox = new Polygon();
    polyForBox.setVertices(rawPoints);

    Rectangle boundingRect = polyForBox.getBoundingRectangle();
    float boxX = boundingRect.x;
    float boxY = boundingRect.y;
    float boxW = boundingRect.getWidth();
    float boxH = boundingRect.getHeight();

    Vector2 aabbCenter = new Vector2(boxX + boxW / 2, boxY + boxH / 2);
    defPoly.position.set(x, y);

    Tabody regularPoly = new Tabody();
    regularPoly.body = world.createBody(defPoly);
    //regularPoly.body.setFixedRotation(true);
    polygonShape = new PolygonShape();

    //polygonShape.setAsBox(w / 2, h / 2);
    for (int i = 0; i < rawPoints.length - 1; i += 2) {
        rawPoints[i] -= aabbCenter.x;
        rawPoints[i + 1] -= aabbCenter.y;
    }
    //rawPoints[0] += 0.5;
    polygonShape.set(rawPoints);

    FixtureDef fixtureBox = new FixtureDef();
    fixtureBox.shape = polygonShape;
    fixtureBox.density = 1;
    fixtureBox.friction = 1;
    fixtureBox.restitution = 0;

    ////////////////////////////////////////
    regularPoly.w = boxW * meterSize;//radius * 2 * meterSize;
    regularPoly.h = boxH * meterSize;//radius * 2 * meterSize;
    regularPoly.fixture = fixtureBox;
    regularPoly.bodyType = "poly";
    ////////////////////////////////////////

    regularPoly.body.createFixture(fixtureBox);
    polygonShape.dispose();
    tabodies.add(regularPoly);
    return regularPoly;
}

From source file:Tabox2D.java

License:Open Source License

/**
 * Creates a Polygons with the given points
 * @param type "dynamic" or "static"/*from  ww w  .j  a  v a 2s  .  c  o m*/
 * @param pts points for the polygon
 * @return A new Tabody instance
 */
public Tabody newPoly(String type, float[] pts) {
    // Scale proportions:
    for (int i = 0; i < pts.length; i++) {
        pts[i] /= meterSize;
    }

    PolygonShape polygonShape;
    BodyDef defPoly = new BodyDef();

    setType(defPoly, type);

    // Get bounding box:

    Polygon polyForBox = new Polygon();
    polyForBox.setVertices(pts);

    //polyForBox.translate(center.x, center.y);

    Rectangle boundingRect = boundingBoxOf(polyForBox.getVertices());
    Vector2 aabbCenter = new Vector2(boundingRect.x + boundingRect.width / 2,
            boundingRect.y + boundingRect.height / 2);
    defPoly.position.set(aabbCenter.x, aabbCenter.y);

    Tabody regularPoly = new Tabody();
    regularPoly.body = world.createBody(defPoly);
    polygonShape = new PolygonShape();

    for (int i = 0; i < pts.length - 1; i += 2) {
        pts[i] -= aabbCenter.x;
        pts[i + 1] -= aabbCenter.y;
    }
    polygonShape.set(pts);

    FixtureDef fixtureBox = new FixtureDef();
    fixtureBox.shape = polygonShape;
    fixtureBox.density = 1;
    fixtureBox.friction = 1;
    fixtureBox.restitution = 0;

    ////////////////////////////////////////
    regularPoly.w = boundingRect.width * meterSize;//radius * 2 * meterSize;
    regularPoly.h = boundingRect.height * meterSize;//radius * 2 * meterSize;
    regularPoly.fixture = fixtureBox;
    regularPoly.bodyType = "poly";
    ////////////////////////////////////////

    regularPoly.body.createFixture(fixtureBox);
    polygonShape.dispose();
    tabodies.add(regularPoly);
    return regularPoly;
}

From source file:Tabox2D.java

License:Open Source License

/**
 * Combines different tabodies in a single one.<br/>
 * This is useful to have a body with different fixtures in an easy way
 * @param tabodyArray Array of tabodies to combine
 * @return A new Tabody//from   ww w  . j a  v a 2  s. c o m
 */
public Tabody combine(String type, Tabody... tabodyArray) {
    if (tabodyArray.length > 0) {

        Tabody newTabody = new Tabody();

        BodyDef bodyDef = new BodyDef();
        setType(bodyDef, type);

        //List<Vector2> centers = new ArrayList<Vector2>();

        //AABB center of combines bodies:
        List<Vector2> ptsCombined = new ArrayList<Vector2>();
        for (int i = 0; i < tabodyArray.length; i++) {
            //centers.add(tabodyArray[i].body.getWorldCenter());
            Tabody t = tabodyArray[i];
            for (Fixture f : t.body.getFixtureList()) {
                if (f.getShape() instanceof CircleShape) {
                    CircleShape cS = (CircleShape) f.getShape();
                    // top-left and bottom-right of circle bounds:
                    ptsCombined.add(new Vector2(cS.getPosition().x - cS.getRadius(),
                            cS.getPosition().y + cS.getRadius()));
                    ptsCombined.add(new Vector2(cS.getPosition().x + cS.getRadius(),
                            cS.getPosition().y - cS.getRadius()));
                } else if (f.getShape() instanceof PolygonShape) {
                    PolygonShape pS = (PolygonShape) f.getShape();
                    for (int n = 0; n < pS.getVertexCount(); n++) {
                        Vector2 tmp = new Vector2();
                        pS.getVertex(n, tmp);
                        ptsCombined.add(
                                new Vector2(t.body.getPosition().x + tmp.x, t.body.getPosition().y + tmp.y));
                    }
                }
            }
        }

        Rectangle rectangle = boundingBoxOf(ptsCombined);

        bodyDef.position.set(rectangle.x + rectangle.width / 2, rectangle.y + rectangle.height / 2);

        newTabody.w = rectangle.width * meterSize;
        newTabody.h = rectangle.height * meterSize;
        newTabody.body = world.createBody(bodyDef);

        for (int i = 0; i < tabodyArray.length; i++) {

            Tabody t = tabodyArray[i];

            for (Fixture f : t.body.getFixtureList()) {
                FixtureDef fixtureDef = new FixtureDef();

                fixtureDef.density = f.getDensity();
                fixtureDef.friction = f.getFriction();
                fixtureDef.restitution = f.getRestitution();
                // Delta X and Y for translating the shapes:
                float dx = t.body.getWorldCenter().x - bodyDef.position.x;
                float dy = t.body.getWorldCenter().y - bodyDef.position.y;
                if (f.getShape() instanceof CircleShape) {

                    CircleShape circleShape = (CircleShape) f.getShape();
                    circleShape.setPosition(
                            new Vector2(circleShape.getPosition().x + dx, circleShape.getPosition().y + dy));
                    fixtureDef.shape = circleShape;

                } else if (f.getShape() instanceof PolygonShape) {

                    PolygonShape polygonShape = (PolygonShape) f.getShape();

                    float[] pts = new float[polygonShape.getVertexCount() * 2];
                    int vertexIndex = 0;
                    // delta X and delta Y respect to the main body:
                    dx = t.body.getPosition().x - bodyDef.position.x;
                    dy = t.body.getPosition().y - bodyDef.position.y;
                    for (int j = 0; j < pts.length - 1; j += 2) {
                        Vector2 tmp = new Vector2();
                        polygonShape.getVertex(vertexIndex, tmp);
                        pts[j] = tmp.x + dx;
                        pts[j + 1] = tmp.y + dy;
                        vertexIndex++;
                    }
                    polygonShape.set(pts);
                    fixtureDef.shape = polygonShape;

                } else if (f.getShape() instanceof EdgeShape) {
                    EdgeShape edgeShape = (EdgeShape) f.getShape();
                    fixtureDef.shape = edgeShape;
                }

                newTabody.body.createFixture(fixtureDef);
            }
        }

        // Destroy:
        for (int i = 0; i < tabodyArray.length; i++) {
            world.destroyBody(tabodyArray[i].body);
            tabodies.remove(tabodyArray[i]);
        }

        // Add new Tabody:
        tabodies.add(newTabody);
        return newTabody;
    } else {
        System.err.println("No tabodies specified in Tabox2D.combine()");
        return null;
    }
}

From source file:com.agateau.pixelwheels.racer.Wheel.java

License:Open Source License

public Wheel(GameWorld gameWorld, Vehicle vehicle, TextureRegion region, float posX, float posY, float angle) {
    mGameWorld = gameWorld;//  www.j  av a2  s  . c  o  m
    mVehicle = vehicle;
    mRegion = region;

    float w = Constants.UNIT_FOR_PIXEL * region.getRegionWidth();
    float h = Constants.UNIT_FOR_PIXEL * region.getRegionHeight();

    BodyDef bodyDef = new BodyDef();
    bodyDef.type = BodyDef.BodyType.DynamicBody;
    bodyDef.position.set(posX, posY);
    bodyDef.angle = angle * MathUtils.degreesToRadians;
    mBody = mGameWorld.getBox2DWorld().createBody(bodyDef);

    PolygonShape shape = new PolygonShape();
    shape.set(Box2DUtils.createOctogon(w, h, w / 4, w / 4));
    mBody.createFixture(shape, 2f);
    shape.dispose();
}

From source file:com.agateau.pixelwheels.utils.Box2DUtils.java

License:Open Source License

public static Body createStaticBodyForMapObject(World world, MapObject object) {
    final float u = Constants.UNIT_FOR_PIXEL;
    float rotation = object.getProperties().get("rotation", 0f, Float.class);

    BodyDef bodyDef = new BodyDef();
    bodyDef.type = BodyDef.BodyType.StaticBody;
    bodyDef.angle = -rotation * MathUtils.degreesToRadians;

    if (object instanceof RectangleMapObject) {
        Rectangle rect = ((RectangleMapObject) object).getRectangle();

        /*/*from  w  w  w .  j a v a  2 s . c o m*/
          A          D
           x--------x
           |        |
           x--------x
          B          C
         */
        float[] vertices = new float[8];
        // A
        vertices[0] = 0;
        vertices[1] = 0;
        // B
        vertices[2] = 0;
        vertices[3] = -rect.getHeight();
        // C
        vertices[4] = rect.getWidth();
        vertices[5] = -rect.getHeight();
        // D
        vertices[6] = rect.getWidth();
        vertices[7] = 0;
        scaleVertices(vertices, u);

        bodyDef.position.set(u * rect.getX(), u * (rect.getY() + rect.getHeight()));
        Body body = world.createBody(bodyDef);

        PolygonShape shape = new PolygonShape();
        shape.set(vertices);

        body.createFixture(shape, 1);
        return body;
    } else if (object instanceof PolygonMapObject) {
        Polygon polygon = ((PolygonMapObject) object).getPolygon();
        float[] vertices = polygon.getVertices().clone();
        scaleVertices(vertices, u);

        bodyDef.position.set(polygon.getX() * u, polygon.getY() * u);
        Body body = world.createBody(bodyDef);

        PolygonShape shape = new PolygonShape();
        shape.set(vertices);

        body.createFixture(shape, 1);
        return body;
    } else if (object instanceof EllipseMapObject) {
        Ellipse ellipse = ((EllipseMapObject) object).getEllipse();
        float radius = ellipse.width * u / 2;
        float x = ellipse.x * u + radius;
        float y = ellipse.y * u + radius;

        bodyDef.position.set(x, y);
        Body body = world.createBody(bodyDef);

        CircleShape shape = new CircleShape();
        shape.setRadius(radius);

        body.createFixture(shape, 1);
        return body;
    }
    throw new RuntimeException("Unsupported MapObject type: " + object);
}

From source file:com.agateau.pixelwheels.utils.Box2DUtils.java

License:Open Source License

public static Shape createBox2DShape(Shape2D shape2D, float zoomFactor) {
    if (shape2D instanceof Polygon) {
        float[] polygonVertices = ((Polygon) shape2D).getTransformedVertices();
        PolygonShape shape = new PolygonShape();
        float[] vertices = Arrays.copyOf(polygonVertices, polygonVertices.length);
        scaleVertices(vertices, zoomFactor);
        shape.set(vertices);
        return shape;
    } else {//from   w ww. ja va 2s  .co  m
        throw new RuntimeException("Unsupported Shape2D type " + shape2D);
    }
}

From source file:com.badlogic.gdx.tests.box2d.ApplyForce.java

License:Apache License

@Override
protected void createWorld(World world) {
    world.setGravity(new Vector2(0, 0));

    float k_restitution = 0.4f;
    Body ground;/*from  w w  w.  j ava2s .c  o m*/

    {
        BodyDef bd = new BodyDef();
        bd.position.set(0, 20);
        ground = world.createBody(bd);

        EdgeShape shape = new EdgeShape();

        FixtureDef sd = new FixtureDef();
        sd.shape = shape;
        sd.density = 0;
        sd.restitution = k_restitution;

        shape.set(new Vector2(-20, -20), new Vector2(-20, 20));
        ground.createFixture(sd);

        shape.set(new Vector2(20, -20), new Vector2(20, 20));
        ground.createFixture(sd);

        shape.set(new Vector2(-20, 20), new Vector2(20, 20));
        ground.createFixture(sd);

        shape.set(new Vector2(-20, -20), new Vector2(20, -20));
        ground.createFixture(sd);

        shape.dispose();
    }

    {
        Transform xf1 = new Transform(new Vector2(), 0.3524f * (float) Math.PI);
        xf1.setPosition(xf1.mul(new Vector2(1, 0)));

        Vector2[] vertices = new Vector2[3];
        vertices[0] = xf1.mul(new Vector2(-1, 0));
        vertices[1] = xf1.mul(new Vector2(1, 0));
        vertices[2] = xf1.mul(new Vector2(0, 0.5f));

        PolygonShape poly1 = new PolygonShape();
        poly1.set(vertices);

        FixtureDef sd1 = new FixtureDef();
        sd1.shape = poly1;
        sd1.density = 4.0f;

        Transform xf2 = new Transform(new Vector2(), -0.3524f * (float) Math.PI);
        xf2.setPosition(xf2.mul(new Vector2(-1, 0)));

        vertices[0] = xf2.mul(new Vector2(-1, 0));
        vertices[1] = xf2.mul(new Vector2(1, 0));
        vertices[2] = xf2.mul(new Vector2(0, 0.5f));

        PolygonShape poly2 = new PolygonShape();
        poly2.set(vertices);

        FixtureDef sd2 = new FixtureDef();
        sd2.shape = poly2;
        sd2.density = 2.0f;

        BodyDef bd = new BodyDef();
        bd.type = BodyType.DynamicBody;
        bd.angularDamping = 5.0f;
        bd.linearDamping = 0.1f;

        bd.position.set(0, 2);
        bd.angle = (float) Math.PI;
        bd.allowSleep = false;
        m_body = world.createBody(bd);
        m_body.createFixture(sd1);
        m_body.createFixture(sd2);
        poly1.dispose();
        poly2.dispose();
    }

    {
        PolygonShape shape = new PolygonShape();
        shape.setAsBox(0.5f, 0.5f);

        FixtureDef fd = new FixtureDef();
        fd.shape = shape;
        fd.density = 1.0f;
        fd.friction = 0.3f;

        for (int i = 0; i < 10; i++) {
            BodyDef bd = new BodyDef();
            bd.type = BodyType.DynamicBody;

            bd.position.set(0, 5 + 1.54f * i);
            Body body = world.createBody(bd);

            body.createFixture(fd);

            float gravity = 10.0f;
            float I = body.getInertia();
            float mass = body.getMass();

            float radius = (float) Math.sqrt(2 * I / mass);

            FrictionJointDef jd = new FrictionJointDef();
            jd.localAnchorA.set(0, 0);
            jd.localAnchorB.set(0, 0);
            jd.bodyA = ground;
            jd.bodyB = body;
            jd.collideConnected = true;
            jd.maxForce = mass * gravity;
            jd.maxTorque = mass * radius * gravity;

            world.createJoint(jd);
        }

        shape.dispose();
    }
}

From source file:com.badlogic.gdx.tests.box2d.CollisionFiltering.java

License:Apache License

@Override
protected void createWorld(World world) {
    {/*from  www. j  a  va2s.c om*/
        EdgeShape shape = new EdgeShape();
        shape.set(new Vector2(-40.0f, 0), new Vector2(40, 0));

        FixtureDef fd = new FixtureDef();
        fd.shape = shape;
        fd.friction = 0.3f;

        BodyDef bd = new BodyDef();
        Body ground = world.createBody(bd);
        ground.createFixture(fd);
        shape.dispose();
    }

    Vector2[] vertices = new Vector2[3];
    vertices[0] = new Vector2(-1, 0);
    vertices[1] = new Vector2(1, 0);
    vertices[2] = new Vector2(0, 2);
    PolygonShape polygon = new PolygonShape();
    polygon.set(vertices);

    FixtureDef triangleShapeDef = new FixtureDef();
    triangleShapeDef.shape = polygon;
    triangleShapeDef.density = 1.0f;

    triangleShapeDef.filter.groupIndex = k_smallGroup;
    triangleShapeDef.filter.categoryBits = k_triangleCategory;
    triangleShapeDef.filter.maskBits = k_triangleMask;

    BodyDef triangleBodyDef = new BodyDef();
    triangleBodyDef.type = BodyType.DynamicBody;
    triangleBodyDef.position.set(-5, 2);

    Body body1 = world.createBody(triangleBodyDef);
    body1.createFixture(triangleShapeDef);

    vertices[0].scl(2);
    vertices[1].scl(2);
    vertices[2].scl(2);

    polygon.set(vertices);
    triangleShapeDef.filter.groupIndex = k_largeGroup;
    triangleBodyDef.position.set(-5, 6);
    triangleBodyDef.fixedRotation = true;

    Body body2 = world.createBody(triangleBodyDef);
    body2.createFixture(triangleShapeDef);

    {
        BodyDef bd = new BodyDef();
        bd.type = BodyType.DynamicBody;
        bd.position.set(-5, 10);
        Body body = world.createBody(bd);

        PolygonShape p = new PolygonShape();
        p.setAsBox(0.5f, 1.0f);
        body.createFixture(p, 1);

        PrismaticJointDef jd = new PrismaticJointDef();
        jd.bodyA = body2;
        jd.bodyB = body;
        jd.enableLimit = true;
        jd.localAnchorA.set(0, 4);
        jd.localAnchorB.set(0, 0);
        jd.localAxisA.set(0, 1);
        jd.lowerTranslation = -1;
        jd.upperTranslation = 1;

        world.createJoint(jd);

        p.dispose();
    }

    polygon.setAsBox(1, 0.5f);
    FixtureDef boxShapeDef = new FixtureDef();
    boxShapeDef.shape = polygon;
    boxShapeDef.density = 1;
    boxShapeDef.restitution = 0.1f;

    boxShapeDef.filter.groupIndex = k_smallGroup;
    boxShapeDef.filter.categoryBits = k_boxCategory;
    boxShapeDef.filter.maskBits = k_boxMask;

    BodyDef boxBodyDef = new BodyDef();
    boxBodyDef.type = BodyType.DynamicBody;
    boxBodyDef.position.set(0, 2);

    Body body3 = world.createBody(boxBodyDef);
    body3.createFixture(boxShapeDef);

    polygon.setAsBox(2, 1);
    boxShapeDef.filter.groupIndex = k_largeGroup;
    boxBodyDef.position.set(0, 6);

    Body body4 = world.createBody(boxBodyDef);
    body4.createFixture(boxShapeDef);

    CircleShape circle = new CircleShape();
    circle.setRadius(1);

    FixtureDef circleShapeDef = new FixtureDef();
    circleShapeDef.shape = circle;
    circleShapeDef.density = 1.0f;

    circleShapeDef.filter.groupIndex = k_smallGroup;
    circleShapeDef.filter.categoryBits = k_circleCategory;
    circleShapeDef.filter.maskBits = k_circleMask;

    BodyDef circleBodyDef = new BodyDef();
    circleBodyDef.type = BodyType.DynamicBody;
    circleBodyDef.position.set(5, 2);

    Body body5 = world.createBody(circleBodyDef);
    body5.createFixture(circleShapeDef);

    circle.setRadius(2);
    circleShapeDef.filter.groupIndex = k_largeGroup;
    circleBodyDef.position.set(5, 6);

    Body body6 = world.createBody(circleBodyDef);
    body6.createFixture(circleShapeDef);
}

From source file:com.esotericsoftware.spine.Box2DExample.java

License:Open Source License

private void createWorld() {
    world = new World(new Vector2(0, -10), true);

    float[] vertices = { -0.07421887f, -0.16276085f, -0.12109375f, -0.22786504f, -0.157552f, -0.7122401f,
            0.04296875f, -0.7122401f, 0.110677004f, -0.6419276f, 0.13151026f, -0.49869835f, 0.08984375f,
            -0.3190109f };/*from  ww w. j  a  v  a 2s  . c o  m*/

    PolygonShape shape = new PolygonShape();
    shape.set(vertices);

    // next we create a static ground platform. This platform
    // is not moveable and will not react to any influences from
    // outside. It will however influence other bodies. First we
    // create a PolygonShape that holds the form of the platform.
    // it will be 100 meters wide and 2 meters high, centered
    // around the origin
    PolygonShape groundPoly = new PolygonShape();
    groundPoly.setAsBox(50, 1);

    // next we create the body for the ground platform. It's
    // simply a static body.
    BodyDef groundBodyDef = new BodyDef();
    groundBodyDef.type = BodyType.StaticBody;
    groundBody = world.createBody(groundBodyDef);

    // finally we add a fixture to the body using the polygon
    // defined above. Note that we have to dispose PolygonShapes
    // and CircleShapes once they are no longer used. This is the
    // only time you have to care explicitely for memomry managment.
    FixtureDef fixtureDef = new FixtureDef();
    fixtureDef.shape = groundPoly;
    fixtureDef.filter.groupIndex = 0;
    groundBody.createFixture(fixtureDef);
    groundPoly.dispose();

    PolygonShape boxPoly = new PolygonShape();
    boxPoly.setAsBox(1, 1);

    // Next we create the 50 box bodies using the PolygonShape we just
    // defined. This process is similar to the one we used for the ground
    // body. Note that we reuse the polygon for each body fixture.
    for (int i = 0; i < 45; i++) {
        // Create the BodyDef, set a random position above the
        // ground and create a new body
        BodyDef boxBodyDef = new BodyDef();
        boxBodyDef.type = BodyType.DynamicBody;
        boxBodyDef.position.x = -24 + (float) (Math.random() * 48);
        boxBodyDef.position.y = 10 + (float) (Math.random() * 100);
        Body boxBody = world.createBody(boxBodyDef);

        boxBody.createFixture(boxPoly, 1);
    }

    // we are done, all that's left is disposing the boxPoly
    boxPoly.dispose();
}

From source file:com.gmail.emersonmx.asteroids.util.PhysicBodyFactory.java

License:Open Source License

private PolygonShape createSpaceshipShape() {
    Vector2[] vertices = createSpaceshipShapeVertices();
    PolygonShape shape = new PolygonShape();
    shape.set(vertices);

    return shape;
}