Example usage for com.badlogic.gdx.maps.objects RectangleMapObject getProperties

List of usage examples for com.badlogic.gdx.maps.objects RectangleMapObject getProperties

Introduction

In this page you can find the example usage for com.badlogic.gdx.maps.objects RectangleMapObject getProperties.

Prototype

public MapProperties getProperties() 

Source Link

Usage

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.
 * //from w  w w . j a v a  2s. 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.prisonbreak.game.MapControlRenderer.java

private void initializeGuards() {
    String type, sheetName, direction;
    guards = new Array<Guard>();

    // extract all guard objects in map
    MapObjects guardObjects = map.getLayers().get("Guards").getObjects();

    // for each object
    for (MapObject guard : guardObjects) {
        RectangleMapObject rectGuard = (RectangleMapObject) guard;

        // if current guard is "not visible" -> ignore
        if (!rectGuard.isVisible()) {
            continue;
        }/*from   w  w w .j a  v  a 2 s  .com*/

        // extract values of attributes of 'guard' object
        type = rectGuard.getProperties().get("type", "none", String.class);
        sheetName = rectGuard.getProperties().get("sheetName", "", String.class);
        if (type.equalsIgnoreCase("none")) {
            Gdx.app.log("Error: ", "'type' attribute not found");
            return;
        }

        // if stationary guard
        if (type.equalsIgnoreCase("stationary")) {
            direction = rectGuard.getProperties().get("direction", "none", String.class);
            if (direction.equalsIgnoreCase("none")) {
                Gdx.app.log("Error: ", "invalid value for direction attribute");
                return;
            }

            // create the specified guard
            Guard specifiedGuard = new StationGuard(sheetName, direction, rectGuard.getRectangle().getX(),
                    rectGuard.getRectangle().getY());
            specifiedGuard.setMapControlRenderer(this);

            // add the corresponding guard to the array
            guards.add(specifiedGuard);
        }
        // if patrol guard
        else if (type.equalsIgnoreCase("patrol")) {
            float secondDelay = rectGuard.getProperties().get("delay", Float.class);

            // create the specified guard (without setting mark points)
            Guard specifiedGuard = new PatrolGuard(sheetName, rectGuard.getRectangle().getX(),
                    rectGuard.getRectangle().getY(), secondDelay);
            specifiedGuard.setMapControlRenderer(this);

            // extract list of mark points from the map
            String listPoints = rectGuard.getProperties().get("markPoints", String.class);
            String[] tileIndices = listPoints.split(",");
            for (int i = 0, indexX, indexY; i < tileIndices.length; i += 2) {
                indexX = Integer.parseInt(tileIndices[i]);
                indexY = Integer.parseInt(tileIndices[i + 1]);

                //                    Gdx.app.log("x: ", "" + indexX);
                //                    Gdx.app.log("y: ", "" + indexY);

                if (!((PatrolGuard) specifiedGuard).addMarkPoint(new Vector2(indexX * 32f, indexY * 32f))) {
                    Gdx.app.log("Cannot add mark point ", "(indeX, indexY)");
                }
            }

            //                Gdx.app.log("Mark point 1: ", ((PatrolGuard) specifiedGuard).listMarkPoints.get(0).toString());
            //                Gdx.app.log("Mark point 2: ", ((PatrolGuard) specifiedGuard).listMarkPoints.get(1).toString());

            // add the corresponding guard to the array
            guards.add(specifiedGuard);
        }
    }
}

From source file:com.prisonbreak.game.MapControlRenderer.java

private Array<Item> triggerInteraction() {
    for (MapObject object : interactionObjects) {
        // all interaction objects are guaranteed to be rectangle
        RectangleMapObject rectObject = (RectangleMapObject) object;
        //            Gdx.app.log("object: ", rectObject.getRectangle().toString());
        //            Gdx.app.log("player: ", player.getSprite().getBoundingRectangle().toString());

        // search and find for the object in interaction with Player
        if (rectObject.getRectangle().overlaps(player.getSprite().getBoundingRectangle())) {
            String directionCheck = rectObject.getProperties().get("contactDirection", "none", String.class);
            //                Gdx.app.log("Contact direction: ", directionCheck);
            //                Gdx.app.log("Player direction: ", player.getCurrentDirection());

            // check if user faces object in correct direction
            if (directionCheck.equalsIgnoreCase("all")
                    || (!player.getCurrentDirection().equalsIgnoreCase("none")
                            && player.getCurrentDirection().equalsIgnoreCase(directionCheck))) {

                // retrieve type of interaction
                String type = rectObject.getProperties().get("type", "", String.class);

                // if searchable objects
                if (type.equalsIgnoreCase("search_interaction")) {
                    interactHappen = true;

                    // set the flag for type of interaction
                    typeInteraction = TYPE_INTERACTION.SEARCH_INTERACTION;

                    // extract attributes' values
                    boolean haveItems = rectObject.getProperties().get("haveItems", false, Boolean.class);
                    int listID = rectObject.getProperties().get("listItemID", -1, Integer.class);

                    // if object does contain items
                    //      -> return list of those items
                    // otherwise -> return null
                    if (haveItems) {
                        // get the item objectItems ID
                        if (listID == -1)
                            break;
                        else
                            return listItems.get(listID);
                    }/*www  . j  a v a 2  s  .  c o  m*/
                }

                // if door object (open_lock_interaction)
                else if (type.equalsIgnoreCase("open_lock_interaction")) {
                    // extract attributes' values
                    boolean locked = rectObject.getProperties().get("locked", false, Boolean.class);
                    int keyID = rectObject.getProperties().get("keyID", -1, Integer.class);
                    Array<Item> needKey = new Array<Item>();
                    Item key = new Item("Needed key", keyID);
                    needKey.add(key);

                    // extract the name of current door in interaction with Player
                    latestObjectName = rectObject.getName();

                    // set the status of current door in interaction with Player
                    latestDoorLocked = locked;
                    //                        Gdx.app.log("locked: ", latestDoorLocked + "");

                    // if the door is not locked
                    //      check the position of Player before invoking interaction
                    //      -> return the required key to lock it
                    if (!latestDoorLocked) {
                        MapObject o = doorObjects.get(latestObjectName);
                        RectangleMapObject r = (RectangleMapObject) o;

                        if (!r.getRectangle().overlaps(player.getSprite().getBoundingRectangle())) {
                            interactHappen = true;

                            // set the flag for type of interaction
                            typeInteraction = TYPE_INTERACTION.OPEN_LOCK_INTERACTION;

                            return needKey;
                        }
                    }
                    // if the door is locked
                    //      -> return the required key to unlock it, or
                    //                the key with keyID = -1 ; indicate
                    //                   that the door CANNOT be opened
                    else {
                        interactHappen = true;

                        // set the flag for type of interaction
                        typeInteraction = TYPE_INTERACTION.OPEN_LOCK_INTERACTION;

                        return needKey;
                    }
                }

                // if readable objects
                else if (type.equalsIgnoreCase("read_interaction")) {
                    interactHappen = true;

                    // set the flag for type of interaction
                    typeInteraction = TYPE_INTERACTION.READ_INTERACTION;

                    // extract attributes' values
                    String message = rectObject.getProperties().get("message", "", String.class);

                    // set the name of the object
                    latestObjectName = rectObject.getProperties().get("name", "Object", String.class);

                    // return a list with one "item" contain the message; id for item = -2
                    Array<Item> l = new Array<Item>();
                    Item mess = new Item("Written Message", -2);
                    mess.setDescription(message);
                    l.add(mess);

                    return l;
                }

                // if password locking objects
                else if (type.equalsIgnoreCase("pass_unlock_interaction")) {
                    boolean locked = rectObject.getProperties().get("locked", false, Boolean.class);

                    // if the object has already been unlocked
                    //      -> return null; no interaction happens
                    if (!locked) {
                        return null;
                    }
                    // otherwise
                    //      -> return a list with first "item" containing the password,
                    //          and all the remaining items are ones that are inside
                    //          the object (in case of safe locker)
                    else {
                        interactHappen = true;

                        // set the flag indicating the type of interaction
                        typeInteraction = TYPE_INTERACTION.PASS_UNLOCK_INTERACTION;

                        // extract the name of object in interaction
                        latestObjectName = rectObject.getName();

                        // extract attributes
                        String password = rectObject.getProperties().get("pass", "", String.class);
                        Item passItem = new Item("Password", -3); // item contains password
                        passItem.setDescription(password);

                        // create the list
                        Array<Item> list = new Array<Item>();
                        list.add(passItem);

                        // if safe locker, add all the contained items into the list
                        int listID = rectObject.getProperties().get("listItemID", -1, Integer.class);
                        if (listID == -1) {
                            Gdx.app.log("Error: ", "listItemID attribute not found");
                        } else {
                            list.addAll(listItems.get(listID));
                        }

                        return list;
                    }
                }

                // if breakable object (here, break the office door)
                else if (type.equalsIgnoreCase("break_interaction")) {
                    boolean broken = rectObject.getProperties().get("broken", true, Boolean.class);

                    // if object has been cracked open (broken = true)
                    //      -> do nothing, no interaction happens, return null
                    if (broken) {
                        return null;
                    }
                    // otherwise
                    //      -> return the required item to break the object (door), which is a crowbar in this game
                    else {
                        interactHappen = true;
                        typeInteraction = TYPE_INTERACTION.BREAK_INTERACTION;

                        // extract the name of object in interaction
                        latestObjectName = rectObject.getName();

                        int id = rectObject.getProperties().get("breakItemID", Integer.class);
                        Item item = new Item("Required Item", id);
                        Array<Item> l = new Array<Item>();
                        l.add(item);

                        return l;
                    }
                }
            }
        }
    }

    return null;
}

From source file:ludowars.model.State.java

public void load() {
    map = new TmxMapLoader().load("assets/maps/forest.tmx");

    int mapWidth = (Integer) map.getProperties().get("width") * (Integer) map.getProperties().get("tilewidth");
    int mapHeight = (Integer) map.getProperties().get("height")
            * (Integer) map.getProperties().get("tileheight");
    int mapSize = Math.max(mapWidth, mapHeight);

    worldBounds = new Rectangle(0, 0, mapWidth, mapHeight);
    entityManager = new EntityManager(new Rectangle(0, 0, mapSize, mapSize));

    CharacterData cool = new CharacterData(new Vector2(356f, 356f), 250, 10);
    cool.width = 16;//from www  .  j  a v a 2  s  . c  o  m
    cool.height = 10;
    cool.controller = "ludowars.controller.PlayerController";
    cool.driver = "ludowars.controller.EntityDriver";
    cool.representation = "ludowars.view.PlayerRepresentation";
    Entity e = entityManager.createEntity(cool);

    for (int i = 0; i < 20; i++) {
        EntityData d = new EntityData();
        d.position.x = MathUtils.random(10, worldBounds.width - 10);
        d.position.y = MathUtils.random(10, worldBounds.height - 10);
        d.width = 18;
        d.height = 16;
        d.controller = "ludowars.controller.HealthPickupController";
        d.representation = "ludowars.view.HealthPickupRepresentation";
        entityManager.createEntity(d);
    }

    // map colliders
    Iterator it = map.getLayers().get("Colliders").getObjects().iterator();
    while (it.hasNext()) {
        RectangleMapObject o = (RectangleMapObject) it.next();

        EntityData d = new EntityData();
        d.position.x = o.getProperties().get("x", Integer.class);
        d.position.y = o.getProperties().get("y", Integer.class);
        d.width = (int) o.getRectangle().width;
        d.height = (int) o.getRectangle().height;
        d.controller = "ludowars.controller.EntityController";
        d.representation = "ludowars.view.NullRepresentation";

        Entity entity = entityManager.createEntity(d);
        entity.setFlag(Entity.ENTITY_COLLIDABLE);
    }
}

From source file:tools.TiledMapHelper.java

License:Apache License

private void loadRectangles(World world) {
    System.out.println("LoadingRectangles");
    Array<RectangleMapObject> objects = getMap().getLayers().get("collision1").getObjects()
            .getByType(RectangleMapObject.class);
    if (objects != null && objects.size != 0) {
        for (int j = 0; j < objects.size; j++) {
            RectangleMapObject obj = objects.get(j);
            //            Iterator it = obj.getProperties().getKeys();
            //            while(it.hasNext()){
            //               System.out.println(it.next());
            //            }
            //            System.out.println("rectangleObject = " + obj.getProperties().get("gameover"));
            GeneralUserData data;/*  w ww. jav a2s.com*/
            if (obj.getProperties().containsKey("gameover")) {
                data = new GameOverData();
            } else {
                data = new PlataformaData();
            }

            createRectangle(world, obj.getRectangle().height / scale, obj.getRectangle().width / scale,
                    //                           obj.getRectangle().x/16, obj.getRectangle().y/1);
                    obj.getRectangle().x / scale, obj.getRectangle().y / scale, data);
        }
    }

}