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

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

Introduction

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

Prototype

public void setAsBox(float hx, float hy) 

Source Link

Document

Build vertices to represent an axis-aligned box.

Usage

From source file:Tabox2D.java

License:Open Source License

/**
 * Creates a new Box body//  ww w  . jav  a  2  s .c o m
 * @param type "dynamic" or "static"
 * @param x Left-bottom corner X of the box
 * @param y Left-bottom corner Y of the box
 * @param w Width of the box
 * @param h Height of the box
 * @return A new Tabody instance
 */
public Tabody newBox(String type, float x, float y, float w, float h) {
    // Scale proportions:
    x = x / meterSize;
    y = y / meterSize;
    w = w / meterSize;
    h = h / meterSize;

    PolygonShape polygonShape;
    BodyDef defBox = new BodyDef();

    setType(defBox, type);

    defBox.position.set(x + w / 2, y + h / 2);

    Tabody box = new Tabody();
    box.body = world.createBody(defBox);
    polygonShape = new PolygonShape();
    polygonShape.setAsBox(w / 2, h / 2);

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

    ////////////////////////////////////////
    box.w = w * meterSize;
    box.h = h * meterSize;
    box.fixture = fixtureBox;
    box.bodyType = "box";
    ////////////////////////////////////////

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

From source file:ch.coldpixel.mario.Sprites.InteractiveTileObject.java

public InteractiveTileObject(World world, TiledMap map, Rectangle bounds) {
    this.world = world;
    this.map = map;
    this.bounds = bounds;

    BodyDef bdef = new BodyDef();
    FixtureDef fdef = new FixtureDef();
    PolygonShape shape = new PolygonShape();

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

    body = world.createBody(bdef);/*from   w w w  .j  a va  2  s.  co  m*/

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

}

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;//from  w w w  . j av a  2s  . c o  m

    //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;
        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.agateau.pixelwheels.bonus.BonusSpot.java

License:Open Source License

public BonusSpot(Assets assets, AudioManager audioManager, GameWorld gameWorld, float x, float y) {
    final float U = Constants.UNIT_FOR_PIXEL;
    mAudioManager = audioManager;//  ww  w . j av a  2s.  c  om
    mX = x;
    mY = y;

    mRegion = assets.gift;
    mSound = assets.soundAtlas.get("bonus");

    PolygonShape shape = new PolygonShape();
    shape.setAsBox(U * mRegion.getRegionWidth() / 2, U * mRegion.getRegionHeight() / 2);

    BodyDef bodyDef = new BodyDef();
    bodyDef.type = BodyDef.BodyType.DynamicBody;
    bodyDef.position.set(mX, mY);

    mBody = gameWorld.getBox2DWorld().createBody(bodyDef);
    Fixture fixture = mBody.createFixture(shape, 1f);
    fixture.setSensor(true);
    mBody.setUserData(this);

    mBody.setAngularVelocity(240 * MathUtils.degreesToRadians);

    shape.dispose();
}

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

License:Open Source License

@SuppressWarnings("unused")
public static Body createStaticBox(World world, float x, float y, float width, float height) {
    BodyDef bodyDef = new BodyDef();
    bodyDef.type = BodyDef.BodyType.StaticBody;
    bodyDef.position.set(x + width / 2, y + height / 2);
    Body body = world.createBody(bodyDef);

    PolygonShape shape = new PolygonShape();
    shape.setAsBox(width / 2, height / 2);

    body.createFixture(shape, 1);/* w  ww . j av  a2s. c o  m*/
    return body;
}

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.
 * /*ww  w .ja  va  2 s.  com*/
 * @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.arkanoid.Actors.BoardActor.java

License:Open Source License

/**
 * Create a new level/*from w  w w  .  j av a2s . co  m*/
 *
 * @param world
 * @param textures
 */
public BoardActor(World world, HashMap<BoardTextures, TextureRegion> textures, Array<TextureRegion> grounds) {
    this.world = world;
    this.textures = textures;
    this.grounds = grounds;

    // left border
    BodyDef def = new BodyDef();
    def.position.set(OFFSET_X - TILE_SIZE / 2f, OFFSET_Y + BOARD_HEIGHT / 2f);
    def.type = BodyDef.BodyType.StaticBody;
    body = world.createBody(def);
    PolygonShape box = new PolygonShape();
    box.setAsBox(TILE_SIZE / 2, BOARD_HEIGHT / 2);
    fixture = body.createFixture(box, 1);
    fixture.setUserData("board_left");
    fixture.setDensity(0f);
    fixture.setRestitution(0f);
    fixture.setFriction(0f);
    box.dispose();

    // right border
    def = new BodyDef();
    def.position.set(OFFSET_X + BOARD_WIDTH + TILE_SIZE / 2f, OFFSET_Y + BOARD_HEIGHT / 2f);
    def.type = BodyDef.BodyType.StaticBody;
    body = world.createBody(def);
    box = new PolygonShape();
    box.setAsBox(TILE_SIZE / 2, BOARD_HEIGHT / 2);
    fixture = body.createFixture(box, 1);
    fixture.setUserData("board_right");
    fixture.setDensity(0f);
    fixture.setRestitution(0f);
    fixture.setFriction(0f);
    box.dispose();

    // top border
    def = new BodyDef();
    def.position.set(OFFSET_X + BOARD_WIDTH / 2f, OFFSET_Y + BOARD_HEIGHT + TILE_SIZE / 2f);
    def.type = BodyDef.BodyType.StaticBody;
    body = world.createBody(def);
    box = new PolygonShape();
    box.setAsBox(BOARD_WIDTH / 2, TILE_SIZE / 2);
    fixture = body.createFixture(box, 1);
    fixture.setUserData("board_top");
    fixture.setDensity(0f);
    fixture.setRestitution(0f);
    fixture.setFriction(0f);
    box.dispose();
    //        def.position.set(OFFSET_X + width / 2f - border / 2f, OFFSET_Y + height / 2f + border / 2f);

    // Graph size
    setSize(BOARD_WIDTH * PPM, BOARD_HEIGHT * PPM);
    // Graph position
    setPosition(body.getPosition().x * PPM - getWidth() / 2f, body.getPosition().y * PPM - getHeight() / 2f);
}

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

License:Apache License

@Override
protected void createWorld(World world) {
    {//ww w. j  a va2  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.utils.MovingPlatform.java

private Body createBox(World world, BodyType type, float width, float height, float density) {
    BodyDef def = new BodyDef();
    def.type = type;/*  w  w  w  . j  av a  2  s.  c o  m*/
    Body box = world.createBody(def);

    PolygonShape poly = new PolygonShape();
    poly.setAsBox(width, height);
    box.createFixture(poly, density);
    poly.dispose();

    return box;
}

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();/*from   w  w w. ja  v  a 2 s. c  om*/

    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);
            }
        }
    }

}