Example usage for com.badlogic.gdx.physics.box2d Body createFixture

List of usage examples for com.badlogic.gdx.physics.box2d Body createFixture

Introduction

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

Prototype

public Fixture createFixture(FixtureDef def) 

Source Link

Document

Creates a fixture and attach it to this body.

Usage

From source file:be.ac.ucl.lfsab1509.bouboule.game.physicEditor.BodyEditorLoader.java

License:Open Source License

/**
 * Creates and applies the fixtures defined in the editor. The name
 * parameter is used to retrieve the right fixture from the loaded file.
 * <br/><br/>//from ww  w.  ja  va2 s. com
 *
 * The body reference point (the red cross in the tool) is by default
 * located at the bottom left corner of the image. This reference point
 * will be put right over the BodyDef position point. Therefore, you should
 * place this reference point carefully to let you place your body in your
 * world easily with its BodyDef.position point. Note that to draw an image
 * at the position of your body, you will need to know this reference point
 * (see {@link #getOrigin(java.lang.String, float)}.
 * <br/><br/>
 *
 * Also, saved shapes are normalized. As shown in the tool, the width of
 * the image is considered to be always 1 meter. Thus, you need to provide
 * a scale factor so the polygons get resized according to your needs (not
 * every body is 1 meter large in your game, I guess).
 *
 * @param body The Box2d body you want to attach the fixture to.
 * @param name The name of the fixture you want to load.
 * @param fd The fixture parameters to apply to the created body fixture.
 * @param scale The desired scale of the body. The default width is 1.
 */
public void attachFixture(Body body, String name, FixtureDef fd, float scale) {
    RigidBodyModel rbModel = model.rigidBodies.get(name);
    if (rbModel == null)
        throw new RuntimeException("Name '" + name + "' was not found.");

    Vector2 origin = vec.set(rbModel.origin).scl(scale);

    for (int i = 0, n = rbModel.polygons.size(); i < n; i++) {
        PolygonModel polygon = rbModel.polygons.get(i);
        Vector2[] vertices = polygon.buffer;

        for (int ii = 0, nn = vertices.length; ii < nn; ii++) {
            vertices[ii] = newVec().set(polygon.vertices.get(ii)).scl(scale);
            vertices[ii].sub(origin);
        }

        polygonShape.set(vertices);
        fd.shape = polygonShape;
        body.createFixture(fd);

        for (int ii = 0, nn = vertices.length; ii < nn; ii++) {
            free(vertices[ii]);
        }
    }

    for (int i = 0, n = rbModel.circles.size(); i < n; i++) {
        CircleModel circle = rbModel.circles.get(i);
        Vector2 center = newVec().set(circle.center).scl(scale);
        float radius = circle.radius * scale;

        circleShape.setPosition(center);
        circleShape.setRadius(radius);
        fd.shape = circleShape;
        body.createFixture(fd);

        free(center);
    }
}

From source file:ch.coldpixel.mario.Tools.B2WorldCreator.java

public B2WorldCreator(World world, TiledMap map) {
    //Create body and fixture variables
    BodyDef bdef = new BodyDef();
    PolygonShape shape = new PolygonShape();
    FixtureDef fdef = new FixtureDef();
    Body body;

    //create ground bodies/fixture
    for (MapObject object : map.getLayers().get(2).getObjects().getByType(RectangleMapObject.class)) { //get(2) = in TILED from below the 2nd object(starts with 0, so it gets ground)
        Rectangle rect = ((RectangleMapObject) object).getRectangle(); //Get Rectangle Object itself

        bdef.type = BodyDef.BodyType.StaticBody;//3 different bodys, static=selfexplaining, dynamic=typical player, kinematic=not effected by forces like gravity, but can manipulated with velocity, ex: moving plattforms
        bdef.position.set((rect.getX() + rect.getWidth() / 2) / MarioBros.PPM,
                (rect.getY() + rect.getHeight() / 2) / MarioBros.PPM);

        body = world.createBody(bdef);//add body to our world

        shape.setAsBox(rect.getWidth() / 2 / MarioBros.PPM, rect.getHeight() / 2 / MarioBros.PPM);
        fdef.shape = shape;//from  w  w w.j  av a2s .c  om
        body.createFixture(fdef);
    }

    //create pipe bodies/fixture
    for (MapObject object : map.getLayers().get(3).getObjects().getByType(RectangleMapObject.class)) {
        Rectangle rect = ((RectangleMapObject) object).getRectangle();

        bdef.type = BodyDef.BodyType.StaticBody;
        bdef.position.set((rect.getX() + rect.getWidth() / 2) / MarioBros.PPM,
                (rect.getY() + rect.getHeight() / 2) / MarioBros.PPM);

        body = world.createBody(bdef);

        shape.setAsBox(rect.getWidth() / 2 / MarioBros.PPM, rect.getHeight() / 2 / MarioBros.PPM);
        fdef.shape = shape;
        body.createFixture(fdef);
    }

    //create brick bodies/fixture
    for (MapObject object : map.getLayers().get(5).getObjects().getByType(RectangleMapObject.class)) {
        Rectangle rect = ((RectangleMapObject) object).getRectangle();

        new Brick(world, map, rect);

    }

    //create coin bodies/fixtures
    for (MapObject object : map.getLayers().get(4).getObjects().getByType(RectangleMapObject.class)) {
        Rectangle rect = ((RectangleMapObject) object).getRectangle();

        new Coin(world, map, rect);

    }

}

From source file:com.anythingmachine.tiledMaps.TiledMapHelper.java

License:Apache License

/**
 * Reads a file describing the collision boundaries that should be set
 * per-tile and adds static bodies to the boxd world.
 * /*w  w  w  .j a v  a  2 s .  c o  m*/
 * @param collisionsFile
 * @param world
 * @param pixelsPerMeter
 *            the pixels per meter scale used for this world
 */
public void loadCollisions(String collisionsFile, World world, float pixelsPerMeter, int level) {
    /**
     * Detect the tiles and dynamically create a representation of the map
     * layout, for collision detection. Each tile has its own collision
     * rules stored in an associated file.
     * 
     * The file contains lines in this format (one line per type of tile):
     * tileNumber XxY,XxY XxY,XxY
     * 
     * Ex:
     * 
     * 3 0x0,31x0 ... 4 0x0,29x0 29x0,29x31
     * 
     * For a 32x32 tileset, the above describes one line segment for tile #3
     * and two for tile #4. Tile #3 has a line segment across the top. Tile
     * #1 has a line segment across most of the top and a line segment from
     * the top to the bottom, 30 pixels in.
     */

    // FileHandle fh = Gdx.files.internal(collisionsFile);
    // String collisionFile = fh.readString();
    // String lines[] = collisionFile.split("\\r?\\n");

    // HashMap<Integer, ArrayList<LineSegment>> tileCollisionJoints = new
    // HashMap<Integer, ArrayList<LineSegment>>();

    // /**
    // * Some locations on the map (perhaps most locations) are "undefined",
    // * empty space, and will have the tile type 0. This code adds an empty
    // * list of line segments for this "default" tile.
    // */
    // tileCollisionJoints.put(Integer.valueOf(0), new
    // ArrayList<LineSegment>());

    // for (int n = 0; n < lines.length; n++) {
    // String cols[] = lines[n].split(" ");
    // int tileNo = Integer.parseInt(cols[0]);
    //
    // ArrayList<LineSegment> tmp = new ArrayList<LineSegment>();
    //
    // for (int m = 1; m < cols.length; m++) {
    // String coords[] = cols[m].split(",");
    //
    // String start[] = coords[0].split("x");
    // String end[] = coords[1].split("x");
    //
    // tmp.add(new LineSegment(Integer.parseInt(start[0]),
    // Integer.parseInt(start[1]),
    // Integer.parseInt(end[0]), Integer.parseInt(end[1]), ""));
    // }
    //
    // tileCollisionJoints.put(Integer.valueOf(tileNo), tmp);
    // }

    ArrayList<LineSegment> collisionLineSegments = new ArrayList<LineSegment>();

    for (int l = 0; l < getMap().getLayers().getCount(); l++) {
        MapLayer nextLayer = getMap().getLayers().get(l);
        if (!nextLayer.getName().equals("AINODEMAP") && !nextLayer.getName().equals("DOORS")) {
            TiledMapTileLayer layer = (TiledMapTileLayer) nextLayer;
            if (layer.getProperties().containsKey("collide")) {
                for (int y = 0; y < layer.getHeight(); y++) {
                    for (int x = 0; x < layer.getWidth(); x++) {
                        Cell tile = layer.getCell(x, y);
                        if (tile != null) {
                            int tileID = tile.getTile().getId();

                            int start = 0;
                            String type = "";
                            if (tile.getTile().getProperties().containsKey("type")) {
                                type = (String) getMap().getTileSets().getTile(tileID).getProperties()
                                        .get("type");
                            }
                            if (layer.getProperties().containsKey("WALLS")) {
                                type = "WALLS";
                                addOrExtendCollisionLineSegment(x * 32 + 16, y * 32, x * 32 + 16, y * 32 + 32,
                                        collisionLineSegments, type);
                            } else if (layer.getProperties().containsKey("STAIRS")) {
                                if (!type.equals("LEFTSTAIRS")) {
                                    type = "STAIRS";
                                    addOrExtendCollisionLineSegment(x * 32, y * 32, x * 32 + 32, y * 32 + 32,
                                            collisionLineSegments, type);
                                } else {
                                    addOrExtendCollisionLineSegment(x * 32, y * 32 + 32, x * 32 + 32, y * 32,
                                            collisionLineSegments, type);
                                }
                            } else if (layer.getProperties().containsKey("PLATFORMS")) {
                                type = "PLATFORMS";
                                addOrExtendCollisionLineSegment(x * 32, y * 32 + 32, x * 32 + 32, y * 32 + 32,
                                        collisionLineSegments, type);
                            }
                        }
                    }
                }
            }
        } else

        {
            MapObjects objects = nextLayer.getObjects();
            for (MapObject o : objects) {
                RectangleMapObject rect = (RectangleMapObject) o;
                if (rect.getProperties().containsKey("set") || rect.getProperties().containsKey("to_level")) {
                    Rectangle shape = rect.getRectangle();

                    BodyDef nodeBodyDef = new BodyDef();
                    nodeBodyDef.type = BodyDef.BodyType.StaticBody;
                    nodeBodyDef.position.set((shape.x + shape.width * 0.5f) * Util.PIXEL_TO_BOX,
                            (shape.y + shape.height * 0.5f) * Util.PIXEL_TO_BOX);

                    Body nodeBody = GamePlayManager.world.createBody(nodeBodyDef);
                    if (!nextLayer.getName().equals("DOORS")) {
                        String set = (String) rect.getProperties().get("set");
                        nodeBody.setUserData(new AINode(Integer.parseInt(set)));
                    } else {
                        if (rect.getProperties().containsKey("to_level")
                                && rect.getProperties().containsKey("exitX")
                                && rect.getProperties().containsKey("exitY")) {
                            String to_level = (String) rect.getProperties().get("to_level");
                            String xPos = (String) rect.getProperties().get("exitX");
                            String yPos = (String) rect.getProperties().get("exitY");
                            nodeBody.setUserData(new Door(to_level, xPos, yPos));
                        } else {
                            nodeBody.setUserData(new Door("9999", "1024", "256"));

                        }
                    }

                    PolygonShape nodeShape = new PolygonShape();

                    nodeShape.setAsBox(shape.width * 0.5f * Util.PIXEL_TO_BOX,
                            shape.height * 0.5f * Util.PIXEL_TO_BOX);
                    FixtureDef fixture = new FixtureDef();
                    fixture.shape = nodeShape;
                    fixture.isSensor = true;
                    fixture.density = 0;
                    fixture.filter.categoryBits = Util.CATEGORY_PLATFORMS;
                    fixture.filter.maskBits = Util.CATEGORY_NPC | Util.CATEGORY_PLAYER;
                    nodeBody.createFixture(fixture);
                    nodeShape.dispose();
                }
            }
        }
    }

    int platnum = 0;
    for (LineSegment lineSegment : collisionLineSegments)

    {
        BodyDef groundBodyDef = new BodyDef();
        groundBodyDef.type = BodyDef.BodyType.StaticBody;
        groundBodyDef.position.set(0, 0);
        Body groundBody = GamePlayManager.world.createBody(groundBodyDef);
        if (lineSegment.type.equals("STAIRS") || lineSegment.type.equals("LEFTSTAIRS")) {
            groundBody.setUserData(
                    new Stairs("stairs_" + level + "_" + platnum, lineSegment.start(), lineSegment.end()));
        } else if (lineSegment.type.equals("WALLS")) {
            groundBody.setUserData(new Entity().setType(EntityType.WALL));
        } else {
            Platform plat = new Platform("plat_" + level + "_" + platnum, lineSegment.start(),
                    lineSegment.end());
            groundBody.setUserData(plat);
            if (GamePlayManager.lowestPlatInLevel == null
                    || lineSegment.start().y < GamePlayManager.lowestPlatInLevel.getDownPosY()) {
                GamePlayManager.lowestPlatInLevel = plat;
            }
        }
        EdgeShape environmentShape = new EdgeShape();

        environmentShape.set(lineSegment.start().scl(1 / pixelsPerMeter),
                lineSegment.end().scl(1 / pixelsPerMeter));
        FixtureDef fixture = new FixtureDef();
        fixture.shape = environmentShape;
        fixture.isSensor = true;
        fixture.density = 1f;
        fixture.filter.categoryBits = Util.CATEGORY_PLATFORMS;
        fixture.filter.maskBits = Util.CATEGORY_NPC | Util.CATEGORY_PLAYER | Util.CATEGORY_PARTICLES;
        groundBody.createFixture(fixture);
        environmentShape.dispose();
    }

    /**
     * Drawing a boundary around the entire map. We can't use a box because
     * then the world objects would be inside and the physics engine would
     * try to push them out.
     */

    TiledMapTileLayer layer = (TiledMapTileLayer) getMap().getLayers().get(3);

    BodyDef bodydef = new BodyDef();
    bodydef.type = BodyType.StaticBody;
    bodydef.position.set(0, 0);
    Body body = GamePlayManager.world.createBody(bodydef);

    // left wall
    EdgeShape mapBounds = new EdgeShape();
    if (level == 1)

    {
        mapBounds.set(new Vector2(0.0f, 0.0f), new Vector2(0, layer.getHeight() * 32).scl(Util.PIXEL_TO_BOX));
        body.setUserData(new Entity().setType(EntityType.WALL));
        Fixture fixture = body.createFixture(mapBounds, 0);
        Filter filter = new Filter();
        filter.categoryBits = Util.CATEGORY_PLATFORMS;
        filter.maskBits = Util.CATEGORY_NPC | Util.CATEGORY_PLAYER;
        fixture.setFilterData(filter);
    } else

    {
        mapBounds.set(new Vector2(0f * Util.PIXEL_TO_BOX, 0.0f),
                new Vector2(0f, layer.getHeight() * 32).scl(Util.PIXEL_TO_BOX));
        body.setUserData(new LevelWall(level - 1));
        Fixture fixture = body.createFixture(mapBounds, 0);
        Filter filter = new Filter();
        filter.categoryBits = Util.CATEGORY_PLATFORMS;
        filter.maskBits = Util.CATEGORY_NPC | Util.CATEGORY_PLAYER;
        fixture.setFilterData(filter);
    }

    // right wall
    body = GamePlayManager.world.createBody(bodydef);
    body.setUserData(new LevelWall(level + 1));

    EdgeShape mapBounds2 = new EdgeShape();
    mapBounds2.set(new Vector2((layer.getWidth() * 32), 0.0f).scl(Util.PIXEL_TO_BOX),
            new Vector2((layer.getWidth() * 32), layer.getHeight() * 32).scl(Util.PIXEL_TO_BOX));
    Fixture fixture = body.createFixture(mapBounds2, 0);
    Filter filter = new Filter();
    filter.categoryBits = Util.CATEGORY_PLATFORMS;
    filter.maskBits = Util.CATEGORY_NPC | Util.CATEGORY_PLAYER;
    fixture.setFilterData(filter);

    // roof
    body = GamePlayManager.world.createBody(bodydef);
    body.setUserData(new Platform("roof_" + level, new Vector2(0.0f, layer.getHeight() * 32),
            new Vector2(layer.getWidth() * 32, layer.getHeight())));
    EdgeShape mapBounds3 = new EdgeShape();
    mapBounds3.set(new Vector2(0.0f, layer.getHeight() * 32).scl(Util.PIXEL_TO_BOX),
            new Vector2(layer.getWidth() * 32, layer.getHeight() * 32).scl(Util.PIXEL_TO_BOX));
    fixture = body.createFixture(mapBounds3, 0);
    fixture.setFilterData(filter);

    mapBounds.dispose();
    mapBounds2.dispose();
    mapBounds3.dispose();

}

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;

    {/* ww w.j  a v  a 2 s  . 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.BodyTypes.java

License:Apache License

@Override
protected void createWorld(World world) {
    Body ground;

    {//from   ww w  .  j a v  a2s.c om
        BodyDef bd = new BodyDef();
        ground = world.createBody(bd);

        EdgeShape shape = new EdgeShape();
        shape.set(new Vector2(-20, 0), new Vector2(20, 0));

        FixtureDef fd = new FixtureDef();
        fd.shape = shape;
        ground.createFixture(fd);
        shape.dispose();
    }

    {
        BodyDef bd = new BodyDef();
        bd.type = BodyType.DynamicBody;
        bd.position.set(0, 3.0f);
        m_attachment = world.createBody(bd);

        PolygonShape shape = new PolygonShape();
        shape.setAsBox(0.5f, 2.0f);
        m_attachment.createFixture(shape, 2.0f);
        shape.dispose();
    }

    {
        BodyDef bd = new BodyDef();
        bd.type = BodyType.DynamicBody;
        bd.position.set(-4.0f, 5.0f);
        m_platform = world.createBody(bd);

        PolygonShape shape = new PolygonShape();
        shape.setAsBox(0.5f, 4.0f, new Vector2(4.0f, 0), 0.5f * (float) Math.PI);

        FixtureDef fd = new FixtureDef();
        fd.shape = shape;
        fd.friction = 0.6f;
        fd.density = 2.0f;

        m_platform.createFixture(fd);
        shape.dispose();

        RevoluteJointDef rjd = new RevoluteJointDef();
        rjd.initialize(m_attachment, m_platform, new Vector2(0, 5.0f));
        rjd.maxMotorTorque = 50.0f;
        rjd.enableMotor = true;
        world.createJoint(rjd);

        PrismaticJointDef pjd = new PrismaticJointDef();
        pjd.initialize(ground, m_platform, new Vector2(0, 5.0f), new Vector2(1, 0));

        pjd.maxMotorForce = 1000.0f;
        pjd.enableMotor = true;
        pjd.lowerTranslation = -10f;
        pjd.upperTranslation = 10.0f;
        pjd.enableLimit = true;

        world.createJoint(pjd);

        m_speed = 3.0f;
    }

    {
        BodyDef bd = new BodyDef();
        bd.type = BodyType.DynamicBody;
        bd.position.set(0, 8.0f);
        Body body = world.createBody(bd);

        PolygonShape shape = new PolygonShape();
        shape.setAsBox(0.75f, 0.75f);

        FixtureDef fd = new FixtureDef();
        fd.shape = shape;
        fd.friction = 0.6f;
        fd.density = 2.0f;

        body.createFixture(fd);
        shape.dispose();
    }
}

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

License:Apache License

@Override
protected void createWorld(World world) {
    {//from  ww w  .  j av a  2 s  . co m
        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.badlogic.gdx.tests.box2d.ConveyorBelt.java

License:Apache License

@Override
protected void createWorld(World world) {
    world.setContactListener(this);

    // Ground// www  . j  av  a 2s .  c o  m
    {
        BodyDef bodyDef = new BodyDef();
        groundBody = world.createBody(bodyDef);

        EdgeShape shape = new EdgeShape();
        shape.set(new Vector2(-20.0f, 0.0f), new Vector2(20.0f, 0.0f));
        groundBody.createFixture(shape, 0.0f);
    }

    // Platform
    {
        BodyDef bd = new BodyDef();
        bd.position.set(-5.0f, 5.0f);
        Body body = world.createBody(bd);

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

        FixtureDef fd = new FixtureDef();
        fd.shape = shape;
        fd.friction = 0.8f;
        m_platform = body.createFixture(fd);
    }

    // Boxes
    for (int i = 0; i < 5; ++i) {
        BodyDef bd = new BodyDef();
        bd.type = BodyType.DynamicBody;
        bd.position.set(-10.0f + 2.0f * i, 7.0f);
        Body body = world.createBody(bd);

        PolygonShape shape = new PolygonShape();
        shape.setAsBox(0.5f, 0.5f);
        body.createFixture(shape, 20.0f);
    }
}

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

public PhysicalCell(Vector2 pos, Texture texture, World world) {

    // create 3 x 3 mesh

    this.world = world;
    this.texture = texture;
    bodies = new Body[3][3];

    FixtureDef fd = new FixtureDef();
    fd = new FixtureDef();

    //PolygonShape shape = new PolygonShape();
    //shape.setAsBox(physicalSize.x / 6, physicalSize.y / 6);
    CircleShape shape = new CircleShape();
    shape.setRadius(0.2f);/*from  w  w  w  .java  2s  .c om*/

    fd.shape = shape;
    fd.density = 6f;
    fd.friction = 0.0f;
    fd.restitution = 0.0f;

    BodyDef bd = new BodyDef();
    bd.type = BodyType.DynamicBody;

    // body vertices
    float x = pos.x;
    float y = pos.y;
    float dx = physicalSize.x / 2;
    float dy = physicalSize.y / 2;
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            if (i * j == 1)
                continue;
            bd.position.set(x + i * dx, y + j * dy);
            Body body = world.createBody(bd);
            body.createFixture(fd);
            bodies[i][j] = body;
        }
    }
    // central body
    //shape.setAsBox(0, 0);
    bodies[1][1] = world.createBody(bd);
    shape.dispose();

    // edges

    int n = 3;
    float dr = (float) Math.sqrt(dx * dx + dy * dy);
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            Body body = bodies[i][j];
            Body body2;
            if (i < n - 1) {
                body2 = bodies[i + 1][j];
                join(body, body2, dx);
            }

            if (j < n - 1) {
                body2 = bodies[i][j + 1];
                join(body, body2, dy);
            }

            if (i < n - 1 && j < n - 1) {
                body2 = bodies[i + 1][j + 1];
                join(body, body2, dr);
            }

            if (i < n - 1 && j > 0) {
                body2 = bodies[i + 1][j - 1];
                join(body, body2, dr);
            }
        }
    }
}

From source file:com.badman.slingmango.data.ConveyorBelt2.java

License:Apache License

@Override
protected void createWorld(World world) {
    world.setContactListener(this);

    // Ground/* w  w  w  . j ava  2  s  .c  om*/
    {
        BodyDef bodyDef = new BodyDef();
        groundBody = world.createBody(bodyDef);

        EdgeShape shape = new EdgeShape();
        shape.set(new Vector2(-20.0f, 0.0f), new Vector2(20.0f, 0.0f));
        groundBody.createFixture(shape, 0.0f);
    }

    // Platform
    {
        BodyDef bd = new BodyDef();
        bd.position.set(-5.0f, 5.0f);
        Body body = world.createBody(bd);

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

        FixtureDef fd = new FixtureDef();
        fd.shape = shape;
        fd.friction = 0.8f;
        m_platform = body.createFixture(fd);
    }

    // Boxes
    for (int i = 0; i < 5; ++i) {
        /*BodyDef bd = new BodyDef();
        bd.type = BodyType.DynamicBody;
        bd.position.set(-10.0f + 2.0f * i, 7.0f);
        Body body = world.createBody(bd);
                
        PolygonShape shape = new PolygonShape();
        shape.setAsBox(0.5f, 0.5f);
        body.createFixture(shape, 20.0f);*/

        Mango mango = new Mango(world);
        mango.body.setTransform(-10.0f + 2.0f * i, 7.0f, 0);
    }

    texture = new Texture(Gdx.files.internal("basket.png"));
}

From source file:com.barconr.games.marblegame.Physics2D.java

License:Apache License

public void createFixtures(TiledMap tiledmap) {
    int layerHeight = 0, layerWidth = 0;
    float tileWidth = 0, tileHeight = 0;

    ballsListener = new BallContactListener();

    // Load the Tiled map layer and store some relevant variables
    TiledMapTileLayer tilelayer = (TiledMapTileLayer) (tiledmap.getLayers().get(0));
    layerHeight = tilelayer.getHeight();
    layerWidth = tilelayer.getWidth();/* ww w .  j a v a 2 s .  co  m*/

    maze = new Maze(layerWidth, layerHeight);

    tileHeight = tilelayer.getTileHeight();
    tileWidth = tilelayer.getTileWidth();

    System.out.println("Layer height (tiles) = " + layerHeight + " Layer width (tiles) = " + layerWidth
            + " Tile height = " + tileHeight + "tile width = " + tileWidth);
    System.out.println("Tile count = " + tilelayer.getObjects().getCount());
    System.out.println("layer height pixels = " + (layerHeight * tileHeight) + "LAYER WIDTH PIXELS : "
            + (layerWidth * tileWidth));

    //Create the box2d world
    world = new World(new Vector2(0, -9), true);
    world.setContactListener(ballsListener);

    // Loop through the grid reference
    for (int y_pos = 0; y_pos < layerHeight; y_pos++) {

        for (int x_pos = 0; x_pos < layerWidth; x_pos++) {

            boolean impassibleBlock = tilelayer.getCell(x_pos, layerHeight - y_pos - 1).getTile()
                    .getProperties().containsKey("block");

            // If the tile square contains the reference "start"
            // Store this as the start position
            if (tilelayer.getCell(x_pos, layerHeight - y_pos - 1).getTile().getProperties()
                    .containsKey("start")) {
                if (startPosition == null) {
                    System.out.println("x:" + x_pos * tileWidth + " y:" + y_pos * tileHeight);
                    startPosition = new Vector2(x_pos * tileWidth * Assets.METERS_PER_PIXEL,
                            (50 - y_pos) * tileHeight * Assets.METERS_PER_PIXEL);

                }

            }

            //Create a fixture for the end position
            if (tilelayer.getCell(x_pos, layerHeight - y_pos - 1).getTile().getProperties()
                    .containsKey("end")) {
                //Draw box for fixture that is impassible
                PolygonShape squareShape = new PolygonShape();

                BodyDef squareBodyDef = new BodyDef();

                squareBodyDef.type = BodyType.StaticBody; //Static body which won't move
                //Box position
                squareBodyDef.position.set(new Vector2((x_pos * Assets.METERS_PER_PIXEL * tileWidth),
                        (layerHeight - y_pos - 1) * Assets.METERS_PER_PIXEL * tileHeight));
                //Correction for fact Box2Ds squares are half width/height from center point
                squareBodyDef.position.add(tileWidth / 2 * Assets.METERS_PER_PIXEL,
                        tileHeight / 2 * Assets.METERS_PER_PIXEL);

                Body squareBody = world.createBody(squareBodyDef);

                squareShape.setAsBox(tileWidth / 2 * Assets.METERS_PER_PIXEL,
                        tileHeight / 2 * Assets.METERS_PER_PIXEL);
                FixtureDef fixDefSquare = new FixtureDef();

                fixDefSquare.shape = squareShape;
                fixDefSquare.isSensor = true;

                fixDefSquare.density = 0.1f;
                fixDefSquare.restitution = 0.3f;

                Fixture endFix = squareBody.createFixture(fixDefSquare);
                endFix.setSensor(true);
                endFix.setUserData("exit");
            }

            if (impassibleBlock) {

                //Draw box for fixture that blocks

                maze.setMazeUnit(new MazeUnit("block"), x_pos, y_pos);
                //System.out.print("@");      // Draw ascii map in stdout

            } else {
                maze.setMazeUnit(new MazeUnit("passage"), x_pos, y_pos);
            }

        }
        //System.out.println();
    }

    // The players ball
    playerBallBodyDef = new BodyDef();
    playerBallBodyDef.type = BodyType.DynamicBody;

    if (startPosition == null) {
        playerBallBodyDef.position.set(3f, 3f);

    } else {
        playerBallBodyDef.position.set(startPosition.x, startPosition.y);
    }
    playerBallBodyDef.allowSleep = false;

    ballCircleBody = world.createBody(playerBallBodyDef);

    dynamicCircle = new CircleShape();
    dynamicCircle.setRadius(8 / Assets.PIXELS_PER_METER);

    FixtureDef ballFixtureDef = new FixtureDef();
    ballFixtureDef.shape = dynamicCircle;
    ballFixtureDef.density = 0.1f;
    ballFixtureDef.friction = 1f;
    //ballFixtureDef.

    ballFixtureDef.restitution = 0.5f;
    //ballCircleBody.setUserData("ball");
    Fixture fx = ballCircleBody.createFixture(ballFixtureDef);
    fx.setUserData("ball");

    maze.removeExtraBoxes();
    /*
    PolygonShape squareShape = new PolygonShape();
            
    */

    for (int i = 0; i < maze.width; i++) {
        for (int j = 0; j < maze.height; j++) {
            if (maze.mazeUnits[j][i].getType().equals("block")) {
                BodyDef squareBodyDef = new BodyDef();
                PolygonShape squareShape = new PolygonShape();
                squareBodyDef.type = BodyType.StaticBody; //Static body which won't move
                //Box position
                squareBodyDef.position.set(new Vector2((j * Assets.METERS_PER_PIXEL * tileWidth),
                        (layerHeight - i - 1) * Assets.METERS_PER_PIXEL * tileHeight));
                //Correction for fact Box2Ds squares are half width/height from center point
                squareBodyDef.position.add(tileWidth / 2 * Assets.METERS_PER_PIXEL,
                        tileHeight / 2 * Assets.METERS_PER_PIXEL);

                Body squareBody = world.createBody(squareBodyDef);
                //Size of box
                squareShape.setAsBox(tileWidth / 2 * Assets.METERS_PER_PIXEL,
                        tileHeight / 2 * Assets.METERS_PER_PIXEL);
                FixtureDef fixDefSquare = new FixtureDef();
                fixDefSquare.shape = squareShape;
                fixDefSquare.density = 0.1f;
                fixDefSquare.restitution = 0.3f;
                squareBody.createFixture(fixDefSquare);
            }
        }
    }

}