Example usage for com.badlogic.gdx.maps MapObjects iterator

List of usage examples for com.badlogic.gdx.maps MapObjects iterator

Introduction

In this page you can find the example usage for com.badlogic.gdx.maps MapObjects iterator.

Prototype

@Override
public Iterator<MapObject> iterator() 

Source Link

Usage

From source file:com.siondream.core.physics.MapBodyManager.java

License:Open Source License

/**
 * @param map map to be used to create the static bodies. 
 * @param layerName name of the layer that contains the shapes.
 *//*w  ww  .ja v  a 2 s.c  o m*/
public void createPhysics(Map map, String layerName) {
    MapLayer layer = map.getLayers().get(layerName);

    if (layer == null) {
        logger.error("layer " + layerName + " does not exist");
        return;
    }

    MapObjects objects = layer.getObjects();
    Iterator<MapObject> objectIt = objects.iterator();

    while (objectIt.hasNext()) {
        MapObject object = objectIt.next();

        if (object instanceof TextureMapObject) {
            continue;
        }

        Shape shape;
        BodyDef bodyDef = new BodyDef();
        bodyDef.type = BodyDef.BodyType.StaticBody;

        if (object instanceof RectangleMapObject) {
            RectangleMapObject rectangle = (RectangleMapObject) object;
            shape = getRectangle(rectangle);
        } else if (object instanceof PolygonMapObject) {
            shape = getPolygon((PolygonMapObject) object);
        } else if (object instanceof PolylineMapObject) {
            shape = getPolyline((PolylineMapObject) object);
        } else if (object instanceof CircleMapObject) {
            shape = getCircle((CircleMapObject) object);
        } else {
            logger.error("non suported shape " + object);
            continue;
        }

        MapProperties properties = object.getProperties();
        String material = properties.get("material", "default", String.class);
        FixtureDef fixtureDef = materials.get(material);

        if (fixtureDef == null) {
            logger.error("material does not exist " + material + " using default");
            fixtureDef = materials.get("default");
        }

        fixtureDef.shape = shape;
        //fixtureDef.filter.categoryBits = Env.game.getCategoryBitsManager().getCategoryBits("level");

        Body body = world.createBody(bodyDef);
        body.createFixture(fixtureDef);

        bodies.add(body);

        fixtureDef.shape = null;
        shape.dispose();
    }
}

From source file:org.saltosion.pixelprophecy.GameWorld.java

License:Open Source License

/**
 * Loads the TiledMap and creates required stuff for it (Box2D etc.)
 *//*  ww w.j a va  2 s .c  o m*/
private void initMap() {
    TiledMap currMap = this.mapLoader.getMap(currentMap);

    MapLayer objectLayer = currMap.getLayers().get(Globals.WALLS_LAYER);
    Array<RectangleMapObject> objects = objectLayer.getObjects().getByType(RectangleMapObject.class);
    Iterator<RectangleMapObject> objIter = objects.iterator();
    while (objIter.hasNext()) {
        RectangleMapObject obj = objIter.next();
        Rectangle rect = obj.getRectangle();
        BodyDef bodyDef = new BodyDef();
        bodyDef.type = BodyDef.BodyType.StaticBody;
        bodyDef.position.set(rect.getX() * Globals.SPRITE_SCALE + rect.width * Globals.SPRITE_SCALE / 2,
                rect.getY() * Globals.SPRITE_SCALE + rect.height * Globals.SPRITE_SCALE / 2);

        Body body = world.createBody(bodyDef);

        PolygonShape polyShape = new PolygonShape();
        polyShape.setAsBox(rect.width * Globals.SPRITE_SCALE / 2, rect.height * Globals.SPRITE_SCALE / 2);

        FixtureDef fixtureDef = new FixtureDef();
        fixtureDef.shape = polyShape;
        fixtureDef.density = .5f;
        fixtureDef.friction = .4f;

        body.createFixture(fixtureDef);

        polyShape.dispose();
    }
    MapLayer entityLayer = currMap.getLayers().get(Globals.ENTITY_LAYER);
    MapObjects entities = entityLayer.getObjects();
    Iterator<MapObject> entityIter = entities.iterator();
    while (entityIter.hasNext()) {
        MapObject entityObj = entityIter.next();
        MapProperties properties = entityObj.getProperties();
        float x = properties.get("x", Float.class);
        float y = properties.get("y", Float.class);
        if (properties.containsKey("light-color") && properties.containsKey("light-distance")) { // This object emits light!
            String s = properties.get("light-color", String.class);
            float distance = Float.parseFloat(properties.get("light-distance", String.class));
            Color color = Globals.parseColor(s);

            PointLight pl = new PointLight(rayHandler, 1000, color, distance, x * Globals.SPRITE_SCALE,
                    y * Globals.SPRITE_SCALE);
            pl.setSoftnessLength(5f);
        }
        if (entityObj.getName().equals(spawnPointName) && player == null) {
            spawnPoint = new Vector2(x, y).scl(Globals.SPRITE_SCALE);
            player = initPlayer();
        }
    }
}

From source file:releasethekraken.LevelLoader.java

/**
 * Parses the level file and constructs a game world from it, and returns it.
 * Throws an exception if loading failed.
 * @return The newly loaded GameWorld//ww  w  .  j a  va  2 s  . c o m
 */
public GameWorld loadWorld() {
    Gdx.app.log("LevelLoader", "Loading level \"" + this.levelName + "\"");

    MapBodyManager mapBodyManager;
    GameWorld newWorld = new GameWorld(this.levelName);

    //Make a new TiledMap
    TiledMap map = new TmxMapLoader().load(this.levelName + ".tmx");

    float unitScale = 16.0F; //16 pixels = 1 meter

    mapBodyManager = new MapBodyManager(newWorld.getPhysWorld(), unitScale, null, 2);
    mapBodyManager.createPhysics(map, "physics");

    //Get the map properties
    MapProperties properties = map.getProperties();

    //Load world properties
    newWorld.setName(properties.get("levelname", String.class));
    newWorld.setPointsForKraken(Integer.parseInt(properties.get("krakenpoints", String.class)));
    newWorld.setWidth(properties.get("width", Integer.class) * 2);
    newWorld.setHeight(properties.get("height", Integer.class) * 2);
    newWorld.setTiledMap(map);
    newWorld.setTiledMapUnitScale(unitScale);
    newWorld.spawnWorldBoundaries();

    //Load Entity Tile Data
    Gdx.app.log("LevelLoader", "Parsing entity tile data");

    TiledMapTileSet entityTileSet = map.getTileSets().getTileSet("Entities");
    Iterator<TiledMapTile> entityTileIterator = entityTileSet.iterator();

    while (entityTileIterator.hasNext()) //Iterate through entity tiles
    {
        TiledMapTile tile = entityTileIterator.next();
        String type = tile.getProperties().get("type", String.class);

        if (type == null) //Only check tiles that have a type set
            continue;

        //See if there is an entity class for a given name
        Class<? extends Entity> entityClass = ReleaseTheKraken.getEntityFromName(type);

        //If there is, register the ID
        if (entityClass != null)
            this.entityTileIDs.put(tile.getId(), entityClass);

        Gdx.app.log("LevelLoader", "Tile ID: " + tile.getId() + " type: " + type);
    }

    //If you thought that was complicated, wait until you see what's next: paths!

    //Load world paths
    Gdx.app.log("LevelLoader", "Parsing world paths");
    MapLayer pathLayer = map.getLayers().get("paths");

    //If the layer doesn't exist, throw an exception
    if (pathLayer == null)
        throw new NullPointerException("paths layer is null");

    MapObjects pathObjects = pathLayer.getObjects();
    Iterator<MapObject> pathObjIterator = pathObjects.iterator();

    //Create an IntMap to map integer path IDs to paths
    IntMap<SeaCreaturePath> pathMap = new IntMap<SeaCreaturePath>();
    //Create an IntMap to map integer path IDs to arrays of next path IDs
    IntMap<int[]> nextPathsMap = new IntMap<int[]>();

    while (pathObjIterator.hasNext()) //Iterate over paths on the map
    {
        MapObject pathObject = pathObjIterator.next();

        //Gdx.app.log("LevelLoader", "Parsing map object: " + pathObject);

        if (pathObject instanceof PolylineMapObject) //If the mapObject is of the correct type
        {
            PolylineMapObject polylineMapObject = (PolylineMapObject) pathObject;

            int pathID = polylineMapObject.getProperties().get("id", Integer.class);

            Gdx.app.log("LevelLoader", "Attempting to load path with ID: " + pathID);

            //Get and parse the list of next paths
            String nextPaths = polylineMapObject.getProperties().get("next", String.class);
            String[] nextPathIDs = nextPaths.split(",");

            //Make an array of next path integer IDs
            int[] nextPathIntIDs = new int[nextPathIDs.length];

            //Parse the integer IDs from the string IDs
            for (int i = 0; i < nextPathIDs.length; i++)
                if (!nextPathIDs[i].equals(""))
                    nextPathIntIDs[i] = Integer.parseInt(nextPathIDs[i]);

            //Create a new SeaCreaturePath object
            SeaCreaturePath seaCreaturePath = new SeaCreaturePath(pathID, null, null,
                    polylineMapObject.getPolyline());

            //Add the SeaCreaturePath object and its next paths to the IntMaps
            pathMap.put(pathID, seaCreaturePath); //Add the path to the IntMap so that it can be connected later
            nextPathsMap.put(pathID, nextPathIntIDs); //Add the next paths to the IntMap so that the paths can be connected later
        }
    }

    //Gdx.app.log("LevelLoader", "Done creating paths");
    //Gdx.app.log("LevelLoader", "pathMap: " + pathMap);
    //Gdx.app.log("LevelLoader", "nextPathsMap: " + nextPathsMap);

    //Now that all of the SeaCreaturePaths are created, it's time to connect them

    SeaCreaturePath firstPath = null; //The first path, which will be the one added to the world
    Iterator<IntMap.Entry<SeaCreaturePath>> pathIterator = pathMap.iterator();

    //Iterate over each path, connecting it to the other paths it should be connected to
    while (pathIterator.hasNext()) {
        IntMap.Entry<SeaCreaturePath> currentPathEntry = pathIterator.next();

        int pathID = currentPathEntry.key;
        SeaCreaturePath currentPath = currentPathEntry.value;

        //Create the next paths list
        Array<SeaCreaturePath> nextPaths = new Array<SeaCreaturePath>();

        //Get the array of next path IDs
        int[] nextPathIDs = nextPathsMap.get(pathID);

        //Connect the paths
        for (int i = 0; i < nextPathIDs.length; i++) {
            nextPaths.add(pathMap.get(nextPathIDs[i])); //Add the path to the list of next paths

            if (pathMap.get(nextPathIDs[i]) != null)
                pathMap.get(nextPathIDs[i]).setParent(currentPath); //Tell the next path that this current path is the parent
            //BUG: Each next path overwrites this, only the last "next path" gets to be the parent
        }

        currentPath.setNextPaths(nextPaths); //Set the next paths list for the path

        //Set the first path to the path that has a null parent
        if (currentPath.getParent() == null)
            firstPath = currentPath;
        //BUG: Only the last path that has a null parent becomes the first path.  
        //This might not be a problem, as only one path should ever have a null parent.
    }

    newWorld.setFirstPath(firstPath); //Set the first path in the world
    //Done loading paths

    //Load world entities
    Gdx.app.log("LevelLoader", "Parsing world entities");
    MapLayer entityLayer = map.getLayers().get("entities");

    //If the layer doesn't exist, throw an exception
    if (entityLayer == null)
        throw new NullPointerException("entities layer is null");

    MapObjects entityObjects = entityLayer.getObjects();
    Iterator<MapObject> entityObjIterator = entityObjects.iterator();

    while (entityObjIterator.hasNext()) //Iterate over entities on the map
    {
        MapObject entityObject = entityObjIterator.next();

        //Gdx.app.log("LevelLoader", "Parsing map object: " + entityObject);

        if (entityObject instanceof TextureMapObject) //If the mapObject is of the correct type
        {
            //Get the entity class from the mapObject's tile ID
            int gid = ((TextureMapObject) entityObject).getProperties().get("gid", Integer.class);
            Class<? extends Entity> entityClass = this.entityTileIDs.get(gid);

            if (entityClass != null) {
                Gdx.app.log("LevelLoader", "Attempting to spawn " + entityClass.getSimpleName());

                try {
                    //Construct a new entity by finding the correct constructor from its class, and reflectively instantiating it.  Magic!
                    Constructor<? extends Entity> constructor = entityClass.getConstructor(GameWorld.class,
                            TextureMapObject.class);
                    Entity entity = constructor.newInstance(newWorld, entityObject);
                    //newWorld.addEntity(entity); //Add the entity to the world //With Box2D, the entity should add itself to the world

                    if (entity instanceof EntityPlayer) //Set the player if the entity is the player
                        newWorld.setPlayer((EntityPlayer) entity);
                    else if (entity instanceof EntityPirateBase) //Set the pirate base if the entity is the pirate base
                        newWorld.setPirateBase((EntityPirateBase) entity);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    Gdx.app.log("LevelLoader", "Successfully loaded the world!");
    Gdx.app.log("LevelLoader", newWorld.toString());

    return newWorld;
}