Example usage for com.badlogic.gdx.maps MapLayer getObjects

List of usage examples for com.badlogic.gdx.maps MapLayer getObjects

Introduction

In this page you can find the example usage for com.badlogic.gdx.maps MapLayer getObjects.

Prototype

public MapObjects getObjects() 

Source Link

Usage

From source file:br.com.animvs.koalory.entities.engine.graphics.tiles.TileRenderer.java

License:Apache License

@Override
public void renderObjects(MapLayer layer) {
    for (MapObject object : layer.getObjects()) {
        renderObject(object);
    }
}

From source file:com.agateau.pixelwheels.map.LapPositionTableIO.java

License:Open Source License

public static LapPositionTable load(TiledMap map) {
    MapLayer layer = map.getLayers().get("Sections");
    Assert.check(layer != null, "No 'Sections' layer found");
    MapObjects objects = layer.getObjects();

    Array<Line> lines = new Array<Line>();
    lines.ensureCapacity(objects.getCount());
    Set<String> names = new HashSet<String>();
    for (MapObject obj : objects) {
        String name = obj.getName();
        Assert.check(!name.isEmpty(), "Section line is missing a name");
        Assert.check(!names.contains(name), "Duplicate section line " + name);
        names.add(name);//from ww w  .j  a  va 2 s .com

        float order;
        try {
            order = Float.parseFloat(name);
        } catch (NumberFormatException e) {
            throw new RuntimeException("Invalid section name " + name);
        }
        Assert.check(obj instanceof PolylineMapObject,
                "'Sections' layer should only contain PolylineMapObjects");
        Polyline polyline = ((PolylineMapObject) obj).getPolyline();
        float[] vertices = polyline.getTransformedVertices();
        Assert.check(vertices.length == 4,
                "Polyline with name " + order + "should have 2 points, not " + (vertices.length / 2));
        Line line = new Line();
        line.x1 = vertices[0];
        line.y1 = vertices[1];
        line.x2 = vertices[2];
        line.y2 = vertices[3];
        line.order = order;
        lines.add(line);
    }
    lines.sort();

    LapPositionTable table = new LapPositionTable();
    for (int idx = 0; idx < lines.size; ++idx) {
        Line line1 = lines.get(idx);
        Line line2 = lines.get((idx + 1) % lines.size);
        float[] vertices = { line1.x1, line1.y1, line2.x1, line2.y1, line2.x2, line2.y2, line1.x2, line1.y2 };
        Polygon polygon = new Polygon(vertices);
        table.addSection(idx, polygon);
    }
    return table;
}

From source file:com.agateau.pixelwheels.map.MapUtils.java

License:Open Source License

public static void renderObjectLayer(ShapeRenderer renderer, MapLayer layer) {
    final float U = Constants.UNIT_FOR_PIXEL;
    for (MapObject object : layer.getObjects()) {
        if (object instanceof PolygonMapObject) {
            float[] vertices = ((PolygonMapObject) object).getPolygon().getTransformedVertices();
            for (int idx = 2; idx < vertices.length; idx += 2) {
                renderer.line(vertices[idx - 2] * U, vertices[idx - 1] * U, vertices[idx] * U,
                        vertices[idx + 1] * U);
            }//w  w  w  . j a v a2  s. com
        } else if (object instanceof RectangleMapObject) {
            Rectangle rect = ((RectangleMapObject) object).getRectangle();
            renderer.rect(rect.x * U, rect.y * U, rect.width * U, rect.height * U);
        }
    }
}

From source file:com.agateau.pixelwheels.map.Track.java

License:Open Source License

public Array<Vector2> findBonusSpotPositions() {
    final float U = Constants.UNIT_FOR_PIXEL;
    MapLayer layer = mMap.getLayers().get("BonusSpots");
    Assert.check(layer != null, "No BonusSpots layer");
    Array<Vector2> lst = new Array<Vector2>();

    for (MapObject object : layer.getObjects()) {
        if (!(object instanceof EllipseMapObject)) {
            throw new RuntimeException(
                    "BonusSpots layer should contains only ellipses. " + object + " is not an ellipse.");
        }/*from   w  w  w  .ja v  a2s  .co m*/
        Ellipse ellipse = ((EllipseMapObject) object).getEllipse();
        Vector2 pos = new Vector2(ellipse.x * U, ellipse.y * U);
        lst.add(pos);
    }
    return lst;
}

From source file:com.agateau.pixelwheels.map.WaypointStore.java

License:Open Source License

public void read(MapLayer layer, LapPositionTable lapPositionTable) {
    final float U = Constants.UNIT_FOR_PIXEL;

    for (MapObject object : layer.getObjects()) {
        Assert.check(object instanceof EllipseMapObject,
                "Waypoints layer should contains only ellipses. " + object + " is not an ellipse.");
        Ellipse ellipse = ((EllipseMapObject) object).getEllipse();
        final LapPosition pos = lapPositionTable.get((int) ellipse.x, (int) ellipse.y);
        WaypointInfo info = new WaypointInfo();
        info.waypoint = new Vector2(ellipse.x * U, ellipse.y * U);
        info.lapDistance = pos.getLapDistance();
        mWaypointInfos.add(info);/*  w w  w. j  a  v  a  2s.c o  m*/
    }
    mWaypointInfos.sort();
}

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.
 * /*  www  . ja v  a2  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.cafeitvn.myballgame.screen.Box2DMapObjectParser.java

License:Apache License

/**
 * creates the given {@link MapLayer MapLayer's} {@link MapObjects} in the given {@link World}  
 * @param world the {@link World} to create the {@link MapObjects} of the given {@link MapLayer} in
 * @param layer the {@link MapLayer} which {@link MapObjects} to create in the given {@link World}
 * @return the given {@link World} with the parsed {@link MapObjects} of the given {@link MapLayer} created in it
 *///from   w w w  .  java  2  s. c  o m
public World load(World world, MapLayer layer) {
    for (MapObject object : layer.getObjects()) {
        if (!ignoreMapUnitScale)
            unitScale = (Float) getProperty(layer.getProperties(), aliases.unitScale, unitScale, Float.class);
        if (object.getProperties().get("type", String.class).equals(aliases.object)) {
            createBody(world, object);
            createFixture(object);
        }
    }

    for (MapObject object : layer.getObjects()) {
        if (!ignoreMapUnitScale)
            unitScale = (Float) getProperty(layer.getProperties(), aliases.unitScale, unitScale, Float.class);
        if (object.getProperties().get("type", String.class).equals(aliases.body))
            createBody(world, object);
    }

    for (MapObject object : layer.getObjects()) {
        if (!ignoreMapUnitScale)
            unitScale = (Float) getProperty(layer.getProperties(), aliases.unitScale, unitScale, Float.class);
        if (object.getProperties().get("type", String.class).equals(aliases.fixture))
            createFixture(object);
    }

    for (MapObject object : layer.getObjects()) {
        if (!ignoreMapUnitScale)
            unitScale = (Float) getProperty(layer.getProperties(), aliases.unitScale, unitScale, Float.class);
        if (object.getProperties().get("type", String.class).equals(aliases.joint))
            createJoint(object);
    }

    return world;
}

From source file:com.cafeitvn.myballgame.screen.Box2DMapObjectParser.java

License:Apache License

/**
 * @param layer the {@link MapLayer} which hierarchy to print
 * @return a human readable {@link String} containing the hierarchy of the {@link MapObjects} of the given {@link MapLayer}
 *//*  w  w w.  ja  v a  2s . c o  m*/
public String getHierarchy(MapLayer layer) {
    String hierarchy = "";

    for (MapObject object : layer.getObjects()) {
        hierarchy += object.getName() + " (" + object.getClass().getSimpleName() + "):\n";
        Iterator<String> keys = object.getProperties().getKeys();
        while (keys.hasNext()) {
            String key = keys.next();
            hierarchy += "\t" + key + ": " + object.getProperties().get(key) + "\n";
        }
    }

    return hierarchy;
}

From source file:com.indignado.games.smariano.utils.dermetfan.box2d.Box2DMapObjectParser.java

License:Apache License

/**
 * creates the given {@link com.badlogic.gdx.maps.MapLayer MapLayer's} {@link com.badlogic.gdx.maps.MapObjects} in the given {@link com.badlogic.gdx.physics.box2d.World}
 *
 * @param world the {@link com.badlogic.gdx.physics.box2d.World} to create the {@link com.badlogic.gdx.maps.MapObjects} of the given {@link com.badlogic.gdx.maps.MapLayer} in
 * @param layer the {@link com.badlogic.gdx.maps.MapLayer} which {@link com.badlogic.gdx.maps.MapObjects} to create in the given {@link com.badlogic.gdx.physics.box2d.World}
 * @return the given {@link com.badlogic.gdx.physics.box2d.World} with the parsed {@link com.badlogic.gdx.maps.MapObjects} of the given {@link com.badlogic.gdx.maps.MapLayer} created in it
 *///from w  w w  . j ava 2  s. com
public World load(World world, MapLayer layer) {
    System.out.println("UNIT SCALE...........:" + unitScale);
    for (MapObject object : layer.getObjects()) {
        if (!ignoreMapUnitScale)
            unitScale = getProperty(layer.getProperties(), aliases.unitScale, unitScale);
        if (object.getProperties().get("type", "", String.class).equals(aliases.modelObject)) {
            createModelObject(world, object);

        }
    }

    for (MapObject object : layer.getObjects()) {
        if (!ignoreMapUnitScale)
            unitScale = getProperty(layer.getProperties(), aliases.unitScale, unitScale);
        if (object.getProperties().get("type", "", String.class).equals(aliases.object)) {
            createBody(world, object);
            createFixtures(object);
        }
    }

    for (MapObject object : layer.getObjects()) {
        if (!ignoreMapUnitScale)
            unitScale = getProperty(layer.getProperties(), aliases.unitScale, unitScale);
        if (object.getProperties().get("type", "", String.class).equals(aliases.body))
            createBody(world, object);
    }

    for (MapObject object : layer.getObjects()) {
        if (!ignoreMapUnitScale)
            unitScale = getProperty(layer.getProperties(), aliases.unitScale, unitScale);
        if (object.getProperties().get("type", "", String.class).equals(aliases.fixture))
            createFixtures(object);
    }

    for (MapObject object : layer.getObjects()) {
        if (!ignoreMapUnitScale)
            unitScale = getProperty(layer.getProperties(), aliases.unitScale, unitScale);
        if (object.getProperties().get("type", "", String.class).equals(aliases.joint))
            createJoint(object);
    }

    return world;
}

From source file:com.indignado.games.smariano.utils.dermetfan.box2d.Box2DMapObjectParser.java

License:Apache License

/**
 * @param layer the {@link com.badlogic.gdx.maps.MapLayer} which hierarchy to print
 * @return a human readable {@link String} containing the hierarchy of the {@link com.badlogic.gdx.maps.MapObjects} of the given {@link com.badlogic.gdx.maps.MapLayer}
 *//*from ww w.java  2  s.  c om*/
public String getHierarchy(MapLayer layer) {
    String hierarchy = "", key;

    for (MapObject object : layer.getObjects()) {
        hierarchy += object.getName() + " (" + object.getClass().getName() + "):\n";
        Iterator<String> keys = object.getProperties().getKeys();
        while (keys.hasNext())
            hierarchy += "\t" + (key = keys.next()) + ": " + object.getProperties().get(key) + "\n";
    }

    return hierarchy;
}