Example usage for com.badlogic.gdx.maps MapObject isVisible

List of usage examples for com.badlogic.gdx.maps MapObject isVisible

Introduction

In this page you can find the example usage for com.badlogic.gdx.maps MapObject isVisible.

Prototype

public boolean isVisible() 

Source Link

Usage

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

License:Apache License

/**
 * creates a {@link Fixture} from a {@link MapObject}
 * @param mapObject the {@link MapObject} which to parse
 * @return the parsed {@link Fixture}/*from w w w .  j a va  2s.co  m*/
 */
public Fixture createFixture(MapObject mapObject) {
    MapProperties properties = mapObject.getProperties();

    String type = properties.get("type", String.class);

    Body body = bodies.get(
            type.equals(aliases.object) ? mapObject.getName() : properties.get(aliases.body, String.class));

    if (!type.equals(aliases.fixture) && !type.equals(aliases.object))
        throw new IllegalArgumentException("type of " + mapObject + " is  \"" + type + "\" instead of \""
                + aliases.fixture + "\" or \"" + aliases.object + "\"");

    FixtureDef fixtureDef = new FixtureDef();
    Shape shape = null;

    if (mapObject instanceof RectangleMapObject) {
        shape = new PolygonShape();
        Rectangle rectangle = ((RectangleMapObject) mapObject).getRectangle();
        rectangle.x *= unitScale;
        rectangle.y *= unitScale;
        rectangle.width *= unitScale;
        rectangle.height *= unitScale;
        ((PolygonShape) shape).setAsBox(rectangle.width / 2, rectangle.height / 2,
                new Vector2(rectangle.x - body.getPosition().x + rectangle.width / 2,
                        rectangle.y - body.getPosition().y + rectangle.height / 2),
                body.getAngle());
    } else if (mapObject instanceof PolygonMapObject) {
        shape = new PolygonShape();
        Polygon polygon = ((PolygonMapObject) mapObject).getPolygon();
        polygon.setPosition(polygon.getX() * unitScale - body.getPosition().x,
                polygon.getY() * unitScale - body.getPosition().y);
        polygon.setScale(unitScale, unitScale);
        ((PolygonShape) shape).set(polygon.getTransformedVertices());
    } else if (mapObject instanceof PolylineMapObject) {
        shape = new ChainShape();
        Polyline polyline = ((PolylineMapObject) mapObject).getPolyline();
        polyline.setPosition(polyline.getX() * unitScale - body.getPosition().x,
                polyline.getY() * unitScale - body.getPosition().y);
        polyline.setScale(unitScale, unitScale);
        ((ChainShape) shape).createChain(polyline.getTransformedVertices());
    } else if (mapObject instanceof CircleMapObject) {
        shape = new CircleShape();
        Circle circle = ((CircleMapObject) mapObject).getCircle();
        circle.setPosition(circle.x * unitScale - body.getPosition().x,
                circle.y * unitScale - body.getPosition().y);
        circle.radius *= unitScale;
        ((CircleShape) shape).setPosition(new Vector2(circle.x, circle.y));
        ((CircleShape) shape).setRadius(circle.radius);
    } else if (mapObject instanceof EllipseMapObject) {
        Ellipse ellipse = ((EllipseMapObject) mapObject).getEllipse();

        if (ellipse.width == ellipse.height) {
            CircleMapObject circleMapObject = new CircleMapObject(ellipse.x, ellipse.y, ellipse.width / 2);
            circleMapObject.setName(mapObject.getName());
            circleMapObject.getProperties().putAll(mapObject.getProperties());
            circleMapObject.setColor(mapObject.getColor());
            circleMapObject.setVisible(mapObject.isVisible());
            circleMapObject.setOpacity(mapObject.getOpacity());
            return createFixture(circleMapObject);
        }

        IllegalArgumentException exception = new IllegalArgumentException(
                "Cannot parse " + mapObject.getName() + " because " + mapObject.getClass().getSimpleName()
                        + "s that are not circles are not supported");
        Gdx.app.error(getClass().getSimpleName(), exception.getMessage(), exception);
        throw exception;
    } else if (mapObject instanceof TextureMapObject) {
        IllegalArgumentException exception = new IllegalArgumentException("Cannot parse " + mapObject.getName()
                + " because " + mapObject.getClass().getSimpleName() + "s are not supported");
        Gdx.app.error(getClass().getSimpleName(), exception.getMessage(), exception);
        throw exception;
    } else
        assert false : mapObject + " is a not known subclass of " + MapObject.class.getName();

    fixtureDef.shape = shape;
    fixtureDef.density = (Float) getProperty(properties, aliases.density, fixtureDef.density, Float.class);
    fixtureDef.filter.categoryBits = (Short) getProperty(properties, aliases.categoryBits,
            fixtureDef.filter.categoryBits, Short.class);
    fixtureDef.filter.groupIndex = (Short) getProperty(properties, aliases.groupIndex,
            fixtureDef.filter.groupIndex, Short.class);
    fixtureDef.filter.maskBits = (Short) getProperty(properties, aliases.maskBits, fixtureDef.filter.maskBits,
            Short.class);
    fixtureDef.friction = (Float) getProperty(properties, aliases.friciton, fixtureDef.friction, Float.class);
    fixtureDef.isSensor = (Boolean) getProperty(properties, aliases.isSensor, fixtureDef.isSensor,
            Boolean.class);
    fixtureDef.restitution = (Float) getProperty(properties, aliases.restitution, fixtureDef.restitution,
            Float.class);

    Fixture fixture = body.createFixture(fixtureDef);

    shape.dispose();

    String name = mapObject.getName();
    if (fixtures.containsKey(name)) {
        int duplicate = 1;
        while (fixtures.containsKey(name + duplicate))
            duplicate++;
        name += duplicate;
    }

    fixtures.put(name, fixture);

    return fixture;
}

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

License:Apache License

/**
 * creates a {@link com.badlogic.gdx.physics.box2d.Fixture} from a {@link com.badlogic.gdx.maps.MapObject}
 *
 * @param mapObject the {@link com.badlogic.gdx.maps.MapObject} to parse
 * @return the parsed {@link com.badlogic.gdx.physics.box2d.Fixture}
 *//*from  w  w  w  . j  a  v  a  2  s.com*/
public Fixture createFixture(MapObject mapObject) {
    MapProperties properties = mapObject.getProperties();

    String type = properties.get("type", String.class);

    Body body = bodies.get(
            type.equals(aliases.object) ? mapObject.getName() : properties.get(aliases.body, String.class));

    if (!type.equals(aliases.fixture) && !type.equals(aliases.object))
        throw new IllegalArgumentException("type of " + mapObject + " is  \"" + type + "\" instead of \""
                + aliases.fixture + "\" or \"" + aliases.object + "\"");

    FixtureDef fixtureDef = new FixtureDef();
    Shape shape = null;

    if (mapObject instanceof RectangleMapObject) {
        shape = new PolygonShape();
        Rectangle rectangle = new Rectangle(((RectangleMapObject) mapObject).getRectangle());
        rectangle.x *= unitScale;
        rectangle.y *= unitScale;
        rectangle.width *= unitScale;
        rectangle.height *= unitScale;
        ((PolygonShape) shape).setAsBox(rectangle.width / 2, rectangle.height / 2,
                new Vector2(rectangle.x - body.getPosition().x + rectangle.width / 2,
                        rectangle.y - body.getPosition().y + rectangle.height / 2),
                body.getAngle());
    } else if (mapObject instanceof PolygonMapObject) {
        shape = new PolygonShape();
        Polygon polygon = ((PolygonMapObject) mapObject).getPolygon();
        polygon.setPosition(polygon.getX() * unitScale - body.getPosition().x,
                polygon.getY() * unitScale - body.getPosition().y);
        polygon.setScale(unitScale, unitScale);
        ((PolygonShape) shape).set(polygon.getTransformedVertices());
    } else if (mapObject instanceof PolylineMapObject) {
        shape = new ChainShape();
        Polyline polyline = ((PolylineMapObject) mapObject).getPolyline();
        polyline.setPosition(polyline.getX() * unitScale - body.getPosition().x,
                polyline.getY() * unitScale - body.getPosition().y);
        polyline.setScale(unitScale, unitScale);
        float[] vertices = polyline.getTransformedVertices();
        Vector2[] vectores = new Vector2[vertices.length / 2];
        for (int i = 0, j = 0; i < vertices.length; i += 2, j++) {
            vectores[j].x = vertices[i];
            vectores[j].y = vertices[i + 1];
        }
        ((ChainShape) shape).createChain(vectores);
    } else if (mapObject instanceof CircleMapObject) {
        shape = new CircleShape();
        Circle circle = ((CircleMapObject) mapObject).getCircle();
        circle.setPosition(circle.x * unitScale - body.getPosition().x,
                circle.y * unitScale - body.getPosition().y);
        circle.radius *= unitScale;
        ((CircleShape) shape).setPosition(new Vector2(circle.x, circle.y));
        ((CircleShape) shape).setRadius(circle.radius);
    } else if (mapObject instanceof EllipseMapObject) {
        Ellipse ellipse = ((EllipseMapObject) mapObject).getEllipse();

        /*
        b2ChainShape* chain = (b2ChainShape*)addr;
        b2Vec2* verticesOut = new b2Vec2[numVertices];
        for( int i = 0; i < numVertices; i++ )
        verticesOut[i] = b2Vec2(verts[i<<1], verts[(i<<1)+1]);
        chain->CreateChain( verticesOut, numVertices );
        delete verticesOut;
        */

        if (ellipse.width == ellipse.height) {
            CircleMapObject circleMapObject = new CircleMapObject(ellipse.x, ellipse.y, ellipse.width / 2);
            circleMapObject.setName(mapObject.getName());
            circleMapObject.getProperties().putAll(mapObject.getProperties());
            circleMapObject.setColor(mapObject.getColor());
            circleMapObject.setVisible(mapObject.isVisible());
            circleMapObject.setOpacity(mapObject.getOpacity());
            return createFixture(circleMapObject);
        }

        IllegalArgumentException exception = new IllegalArgumentException(
                "Cannot parse " + mapObject.getName() + " because  that are not circles are not supported");
        Gdx.app.error(getClass().getName(), exception.getMessage(), exception);
        throw exception;
    } else if (mapObject instanceof TextureMapObject) {
        IllegalArgumentException exception = new IllegalArgumentException(
                "Cannot parse " + mapObject.getName() + " because s are not supported");
        Gdx.app.error(getClass().getName(), exception.getMessage(), exception);
        throw exception;
    } else
        assert false : mapObject + " is a not known subclass of " + MapObject.class.getName();

    fixtureDef.shape = shape;
    fixtureDef.density = getProperty(properties, aliases.density, fixtureDef.density);
    fixtureDef.filter.categoryBits = getProperty(properties, aliases.categoryBits, GRUPO.STATIC.getCategory());
    fixtureDef.filter.groupIndex = getProperty(properties, aliases.groupIndex, fixtureDef.filter.groupIndex);
    fixtureDef.filter.maskBits = getProperty(properties, aliases.maskBits, Box2DPhysicsObject.MASK_STATIC);
    fixtureDef.friction = getProperty(properties, aliases.friciton, fixtureDef.friction);
    fixtureDef.isSensor = getProperty(properties, aliases.isSensor, fixtureDef.isSensor);
    fixtureDef.restitution = getProperty(properties, aliases.restitution, fixtureDef.restitution);

    Fixture fixture = body.createFixture(fixtureDef);
    fixture.setUserData(body.getUserData());
    shape.dispose();

    String name = mapObject.getName();
    if (fixtures.containsKey(name)) {
        int duplicate = 1;
        while (fixtures.containsKey(name + duplicate))
            duplicate++;
        name += duplicate;
    }

    fixtures.put(name, fixture);

    return fixture;
}

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

License:Apache License

/**
 * creates {@link com.badlogic.gdx.physics.box2d.Fixture Fixtures} from a {@link com.badlogic.gdx.maps.MapObject}
 *
 * @param mapObject the {@link com.badlogic.gdx.maps.MapObject} to parse
 * @return an array of parsed {@link com.badlogic.gdx.physics.box2d.Fixture Fixtures}
 *///from  w w  w.j  a  v  a2s  .  c om
public Fixture[] createFixtures(MapObject mapObject) {
    Polygon polygon;

    if (!(mapObject instanceof PolygonMapObject)
            || isConvex(polygon = ((PolygonMapObject) mapObject).getPolygon()))
        return new Fixture[] { createFixture(mapObject) };

    Polygon[] convexPolygons;
    if (triangulate) {
        if (areVerticesClockwise(polygon)) { // ensure the vertices are in counterclockwise order (not really necessary according to EarClippingTriangulator's javadoc, but sometimes better)
            Array<Vector2> vertices = new Array<Vector2>(toVector2Array(polygon.getVertices()));
            Vector2 first = vertices.removeIndex(0);
            vertices.reverse();
            vertices.insert(0, first);
            polygon.setVertices(toFloatArray(vertices.items));
        }
        convexPolygons = toPolygonArray(toVector2Array(
                new EarClippingTriangulator().computeTriangles(polygon.getTransformedVertices()).toArray()), 3);
    } else {
        Array<Array<Vector2>> convexPolys = BayazitDecomposer
                .convexPartition(new Array<Vector2>(toVector2Array(polygon.getTransformedVertices())));
        convexPolygons = new Polygon[convexPolys.size];
        for (int i = 0; i < convexPolygons.length; i++)
            convexPolygons[i] = new Polygon(
                    toFloatArray((Vector2[]) convexPolys.get(i).toArray(Vector2.class)));
    }

    // create the fixtures using the convex polygons
    Fixture[] fixtures = new Fixture[convexPolygons.length];
    for (int i = 0; i < fixtures.length; i++) {
        PolygonMapObject convexObject = new PolygonMapObject(convexPolygons[i]);
        convexObject.setColor(mapObject.getColor());
        convexObject.setName(mapObject.getName());
        convexObject.setOpacity(mapObject.getOpacity());
        convexObject.setVisible(mapObject.isVisible());
        convexObject.getProperties().putAll(mapObject.getProperties());
        fixtures[i] = createFixture(convexObject);
    }

    return fixtures;
}

From source file:com.prisonbreak.game.entities.Character.java

private boolean haveCollision(float newX, float newY) {
    // if out of world map -> no need to check -> stop checking
    if (newX < 0 || newX + width > MapControlRenderer.WORLD_WIDTH || newY < 0
            || newY + height > MapControlRenderer.WORLD_HEIGHT) {
        return true;
    }/* ww  w  . j  av  a2 s .co  m*/

    // get bounding rectangle of current Character
    Rectangle characterBounding = new Rectangle(newX, newY, width, height);

    /* With Guard (when as Player) */

    // if current character == Player
    float offset = 4f;
    if (this instanceof Player) {
        Rectangle rectPlayer = new Rectangle(characterBounding.getX() + offset,
                characterBounding.getY() + offset, characterBounding.getWidth() - 2 * offset,
                characterBounding.getHeight() - 2 * offset);

        // check with Guards
        for (Guard guard : renderer.getListGuards()) {
            Rectangle rectGuard = new Rectangle(guard.getSprite().getBoundingRectangle().getX() + offset,
                    guard.getSprite().getBoundingRectangle().getY() + offset,
                    guard.getSprite().getBoundingRectangle().getWidth() - 2 * offset,
                    guard.getSprite().getBoundingRectangle().getHeight() - 2 * offset);

            if (rectPlayer.overlaps(rectGuard))
                return true;
        }
    }

    /* End */

    /* With static (blocked) objects */

    // consider each objects
    for (MapObject object : renderer.getStaticObjects()) {
        // cast to rectangle object
        if (object.isVisible() && object.getProperties().get("blocked", Boolean.class) != null
                && object.getProperties().get("blocked", Boolean.class)
                && object instanceof RectangleMapObject) {
            RectangleMapObject rectObject = (RectangleMapObject) object;

            // check for overlapping ~ collision
            if (rectObject.getRectangle().overlaps(characterBounding))
                return true;
        }
    }

    /* End */

    /* With locked doors */

    // for each object
    for (MapObject object : renderer.getDoorObjects()) {
        if (object.isVisible() && (object.getProperties().get("locked", null, Boolean.class) != null)
                && object.getProperties().get("locked", Boolean.class)
                && object instanceof RectangleMapObject) {
            RectangleMapObject rectObject = (RectangleMapObject) object;

            if (rectObject.getRectangle().overlaps(characterBounding))
                return true;
        }
    }

    /* End */

    /* With walls */

    // position of two points that bound the Player's image
    int lowerBoundX, lowerBoundY, upperBoundX, upperBoundY, temp;
    float alpha = (float) 0.25;

    temp = (int) (newX / 32f); // account for less than 12.5% of the
    if ((newX / 32f - temp) > (1 - alpha)) { // left tile -> do not consider
        lowerBoundX = temp + 1;
    } else { // otherwise; consider when checking
        lowerBoundX = temp; // for collision
    }

    temp = (int) (newY / 32f); // account for less than 12.5% of the
    if ((newY / 32f - temp) > (1 - alpha)) { // below tile -> do not consider
        lowerBoundY = temp + 1;
    } else {
        lowerBoundY = temp;
    }

    temp = (int) ((newX + width) / 32f); // account for less than 12.5% of the
    if (((newX + width) / 32f - temp) < alpha) { // right tile -> do not consider
        upperBoundX = temp - 1;
    } else {
        upperBoundX = temp;
    }

    temp = (int) ((newY + height) / 32f); // account for less than 12.5% of the
    if (((newY + height) / 32f - temp) < alpha) { // above tile -> do not consider
        upperBoundY = temp - 1;
    } else {
        upperBoundY = temp;
    }

    // check all the tiles (32x32 pixels) the Player's image accounts for
    int[][] grid = renderer.getBlockedWallsGrid();
    for (int i = (int) lowerBoundX; i <= (int) upperBoundX; ++i) {
        for (int j = (int) lowerBoundY; j <= (int) upperBoundY; ++j) {
            if (grid[i][j] == 1)
                return true;
        }
    }

    /* End */

    return false;
}

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

private void extractBlockedWalls() {
    // get map objects of ObjectLayer "Collision"
    MapLayer layer = map.getLayers().get("WallCollision");
    MapObjects objects = layer.getObjects();

    // fill in blockedWallUnitGrid with position of static blocked map objects
    // 1 -> blocked     0 -> not blocked
    blockedWallUnitGrid = new int[100][100];
    boolean isBlocked = false;
    for (int indexX = 0; indexX < 100; ++indexX) {
        for (int indexY = 0; indexY < 100; ++indexY) {
            // convert to position in world map
            Vector2 worldPosition = new Vector2(indexX * 32f + 16f, indexY * 32f + 16f); // consider center

            // check whether that position is "blocked" or not
            for (MapObject o : objects) {
                // retrieve RectangleMapObject objects that are blocked
                if (o.isVisible() && o instanceof RectangleMapObject && o.getProperties().get("blocked") != null
                        && o.getProperties().get("blocked", Boolean.class)) {
                    RectangleMapObject rectObject = (RectangleMapObject) o;

                    if (rectObject.getRectangle().contains(worldPosition)) {
                        isBlocked = true;
                        break;
                    }/*from   www .  j  av  a 2s  .  c  om*/
                }
            }

            // fill 1 / 0 into the corrsponding tile index
            if (isBlocked) {
                blockedWallUnitGrid[indexX][indexY] = 1;
            } else {
                blockedWallUnitGrid[indexX][indexY] = 0;
            }

            // reset flag
            isBlocked = false;
        }
    }

    //        Gdx.app.log("Test: ", " " + blockedWallUnitGrid[13][38] + " " + blockedWallUnitGrid[13][39] +
    //                " " + blockedWallUnitGrid[12][38] + " " + blockedWallUnitGrid[12][39]);
}

From source file:com.stercore.code.net.dermetfan.utils.libgdx.box2d.Box2DMapObjectParser.java

License:Apache License

/** creates {@link Fixture Fixtures} from a {@link MapObject}
 *  @param mapObject the {@link MapObject} to parse
 *  @param body the {@link Body} to create the {@link Fixture Fixtures} on
 *  @return an array of parsed {@link Fixture Fixtures} */
public Fixture[] createFixtures(MapObject mapObject, Body body) {
    if ((mapObject = listener.createFixtures(mapObject)) == null)
        return null;

    Polygon polygon;//  w w w . java2  s  . com

    if (!(mapObject instanceof PolygonMapObject)
            || isConvex(polygon = ((PolygonMapObject) mapObject).getPolygon())
                    && (!Box2DUtils.checkPreconditions
                            || polygon.getVertices().length / 2 <= Box2DUtils.maxPolygonVertices))
        return new Fixture[] { createFixture(mapObject, body) };

    Polygon[] convexPolygons = triangulate ? triangulate(polygon) : decompose(polygon);
    Fixture[] fixtures = new Fixture[convexPolygons.length];
    for (int i = 0; i < fixtures.length; i++) {
        PolygonMapObject convexObject = new PolygonMapObject(convexPolygons[i]);
        convexObject.setColor(mapObject.getColor());
        convexObject.setName(mapObject.getName());
        convexObject.setOpacity(mapObject.getOpacity());
        convexObject.setVisible(mapObject.isVisible());
        convexObject.getProperties().putAll(mapObject.getProperties());
        fixtures[i] = createFixture(convexObject, body);
    }

    return fixtures;
}

From source file:com.stercore.code.net.dermetfan.utils.libgdx.maps.TmxMapWriter.java

License:Apache License

/** @param object the {@link MapObject} to write in TMX format
 *  @return this {@link TmxMapWriter} */
public TmxMapWriter tmx(MapObject object) throws IOException {
    MapProperties props = object.getProperties();
    element("object");
    attribute("name", object.getName());
    if (props.containsKey("type"))
        attribute("type", getProperty(props, "type", ""));
    if (props.containsKey("gid"))
        attribute("gid", getProperty(props, "gid", 0));

    int objectX = getProperty(props, "x", 0);
    int objectY = getProperty(props, "y", 0);

    if (object instanceof RectangleMapObject) {
        Rectangle rect = ((RectangleMapObject) object).getRectangle();
        int height = round(rect.height);
        attribute("x", objectX).attribute("y", toYDown(objectY + height));
        attribute("width", round(rect.width)).attribute("height", height);
    } else if (object instanceof EllipseMapObject) {
        Ellipse ellipse = ((EllipseMapObject) object).getEllipse();
        int height = round(ellipse.height);
        attribute("x", objectX).attribute("y", toYDown(objectY + height));
        attribute("width", round(ellipse.width)).attribute("height", height);
        element("ellipse").pop();
    } else if (object instanceof CircleMapObject) {
        Circle circle = ((CircleMapObject) object).getCircle();
        attribute("x", objectX).attribute("y", objectY);
        attribute("width", round(circle.radius * 2)).attribute("height", round(circle.radius * 2));
        element("ellipse").pop();
    } else if (object instanceof PolygonMapObject) {
        attribute("x", objectX).attribute("y", toYDown(objectY));
        Polygon polygon = ((PolygonMapObject) object).getPolygon();
        element("polygon");
        attribute("points", points(GeometryUtils.toYDown(polygon.getVertices())));
        pop();// w w w.  j  a va2s  .c  o  m
    } else if (object instanceof PolylineMapObject) {
        attribute("x", objectX).attribute("y", toYDown(objectY));
        Polyline polyline = ((PolylineMapObject) object).getPolyline();
        element("polyline");
        attribute("points", points(GeometryUtils.toYDown(polyline.getVertices())));
        pop();
    }

    if (props.containsKey("rotation"))
        attribute("rotation", getProperty(props, "rotation", 0f));
    if (props.containsKey("visible"))
        attribute("visible", object.isVisible() ? 1 : 0);
    if (object.getOpacity() != 1)
        attribute("opacity", object.getOpacity());

    @SuppressWarnings("unchecked")
    Array<String> excludedKeys = Pools.obtain(Array.class);
    excludedKeys.clear();
    excludedKeys.add("type");
    excludedKeys.add("gid");
    excludedKeys.add("x");
    excludedKeys.add("y");
    excludedKeys.add("width");
    excludedKeys.add("height");
    excludedKeys.add("rotation");
    excludedKeys.add("visible");
    excludedKeys.add("opacity");
    tmx(props, excludedKeys);
    excludedKeys.clear();
    Pools.free(excludedKeys);

    pop();
    return this;
}

From source file:net.dermetfan.gdx.physics.box2d.Box2DMapObjectParser.java

License:Apache License

/** creates {@link Fixture Fixtures} from a {@link MapObject}
 *  @param mapObject the {@link MapObject} to parse
 *  @param body the {@link Body} to create the {@link Fixture Fixtures} on
 *  @return an array of parsed {@link Fixture Fixtures} */
public Fixture[] createFixtures(MapObject mapObject, Body body) {
    if ((mapObject = listener.createFixtures(mapObject)) == null)
        return null;

    Polygon polygon;//w  ww  .  ja  v a2 s .c o m

    if (!(mapObject instanceof PolygonMapObject)
            || isConvex(polygon = ((PolygonMapObject) mapObject).getPolygon())
                    && Box2DUtils.check.isValidPolygonShape(polygon.getVertices()))
        return new Fixture[] { createFixture(mapObject, body) };

    Polygon[] convexPolygons = toPolygonArray(triangulate ? triangulate(polygon.getTransformedVertices())
            : decompose(polygon.getTransformedVertices()));
    Fixture[] fixtures = new Fixture[convexPolygons.length];
    for (int i = 0; i < fixtures.length; i++) {
        PolygonMapObject convexObject = new PolygonMapObject(convexPolygons[i]);
        convexObject.setColor(mapObject.getColor());
        convexObject.setName(mapObject.getName());
        convexObject.setOpacity(mapObject.getOpacity());
        convexObject.setVisible(mapObject.isVisible());
        convexObject.getProperties().putAll(mapObject.getProperties());
        fixtures[i] = createFixture(convexObject, body);
    }

    return fixtures;
}

From source file:net.dermetfan.utils.libgdx.box2d.Box2DMapObjectParser.java

License:Apache License

/** creates a {@link Fixture} from a {@link MapObject}
 *  @param mapObject the {@link MapObject} to parse
 *  @param body the {@link Body} to create the {@link Fixture Fixtures} on
 *  @return the parsed {@link Fixture} */
public Fixture createFixture(MapObject mapObject, Body body) {
    MapProperties properties = mapObject.getProperties();

    Shape shape = null;//from  w  ww .ja  v  a 2  s  .  c om
    if (mapObject instanceof RectangleMapObject) {
        shape = new PolygonShape();
        Rectangle rectangle = ((RectangleMapObject) mapObject).getRectangle();
        float x = rectangle.x * unitScale, y = rectangle.y * unitScale, width = rectangle.width * unitScale,
                height = rectangle.height * unitScale;
        ((PolygonShape) shape).setAsBox(width / 2, height / 2,
                vec2.set(x - body.getPosition().x + width / 2, y - body.getPosition().y + height / 2),
                body.getAngle());
    } else if (mapObject instanceof PolygonMapObject) {
        shape = new PolygonShape();
        Polygon polygon = new Polygon(((PolygonMapObject) mapObject).getPolygon().getTransformedVertices());
        polygon.setScale(unitScale, unitScale);
        polygon.setPosition(-body.getPosition().x, -body.getPosition().y);
        ((PolygonShape) shape).set(polygon.getTransformedVertices());
    } else if (mapObject instanceof PolylineMapObject) {
        shape = new ChainShape();
        Polyline polyline = new Polyline(
                ((PolylineMapObject) mapObject).getPolyline().getTransformedVertices());
        polyline.setPosition(polyline.getX() * unitScale - body.getPosition().x,
                polyline.getY() * unitScale - body.getPosition().y);
        polyline.setScale(unitScale, unitScale);
        ((ChainShape) shape).createChain(polyline.getTransformedVertices());
    } else if (mapObject instanceof CircleMapObject) {
        shape = new CircleShape();
        Circle mapObjectCircle = ((CircleMapObject) mapObject).getCircle();
        Circle circle = new Circle(mapObjectCircle.x, mapObjectCircle.y, mapObjectCircle.radius);
        circle.setPosition(circle.x * unitScale - body.getPosition().x,
                circle.y * unitScale - body.getPosition().y);
        circle.radius *= unitScale;
        CircleShape circleShape = (CircleShape) shape;
        circleShape.setPosition(vec2.set(circle.x, circle.y));
        circleShape.setRadius(circle.radius);
    } else if (mapObject instanceof EllipseMapObject) {
        Ellipse ellipse = ((EllipseMapObject) mapObject).getEllipse();

        if (ellipse.width == ellipse.height) {
            CircleMapObject circleMapObject = new CircleMapObject(ellipse.x + ellipse.width / 2,
                    ellipse.y + ellipse.height / 2, ellipse.width / 2);
            circleMapObject.setName(mapObject.getName());
            circleMapObject.getProperties().putAll(mapObject.getProperties());
            circleMapObject.setColor(mapObject.getColor());
            circleMapObject.setVisible(mapObject.isVisible());
            circleMapObject.setOpacity(mapObject.getOpacity());
            return createFixture(circleMapObject, body);
        }

        throw new IllegalArgumentException("Cannot parse " + mapObject.getName() + " because "
                + mapObject.getClass().getSimpleName() + "s that are not circles are not supported");
    } else if (mapObject instanceof TextureMapObject)
        throw new IllegalArgumentException("Cannot parse " + mapObject.getName() + " because "
                + mapObject.getClass().getSimpleName() + "s are not supported");
    else
        assert false : mapObject + " is a not known subclass of " + MapObject.class.getName();

    FixtureDef fixtureDef = new FixtureDef();
    fixtureDef.shape = shape;
    assignProperties(fixtureDef, heritage);
    assignProperties(fixtureDef, mapProperties);
    assignProperties(fixtureDef, layerProperties);
    assignProperties(fixtureDef, properties);

    Fixture fixture = body.createFixture(fixtureDef);
    fixture.setUserData(getProperty(layerProperties, aliases.userData, fixture.getUserData()));
    fixture.setUserData(getProperty(properties, aliases.userData, fixture.getUserData()));

    shape.dispose();

    fixtures.put(findAvailableName(mapObject.getName(), fixtures), fixture);

    return fixture;
}

From source file:net.dermetfan.utils.libgdx.box2d.Box2DMapObjectParser.java

License:Apache License

/** creates {@link Fixture Fixtures} from a {@link MapObject}
 *  @param mapObject the {@link MapObject} to parse
 *  @param body the {@link Body} to create the {@link Fixture Fixtures} on
 *  @return an array of parsed {@link Fixture Fixtures} */
public Fixture[] createFixtures(MapObject mapObject, Body body) {
    Polygon polygon;// w  w w .  j  a v a 2s . c o m

    if (!(mapObject instanceof PolygonMapObject)
            || isConvex(polygon = ((PolygonMapObject) mapObject).getPolygon()))
        return new Fixture[] { createFixture(mapObject, body) };

    Polygon[] convexPolygons;
    if (triangulate) {
        if (areVerticesClockwise(polygon)) { // ensure the vertices are in counterclockwise order (not really necessary according to EarClippingTriangulator's javadoc, but sometimes better)
            Array<Vector2> vertices = new Array<Vector2>(toVector2Array(polygon.getVertices()));
            Vector2 first = vertices.removeIndex(0);
            vertices.reverse();
            vertices.insert(0, first);
            polygon.setVertices(toFloatArray(vertices.items));
        }
        convexPolygons = triangulate(polygon);
    } else
        convexPolygons = decompose(polygon);

    // create the fixtures using the convex polygons
    Fixture[] fixtures = new Fixture[convexPolygons.length];
    for (int i = 0; i < fixtures.length; i++) {
        PolygonMapObject convexObject = new PolygonMapObject(convexPolygons[i]);
        convexObject.setColor(mapObject.getColor());
        convexObject.setName(mapObject.getName());
        convexObject.setOpacity(mapObject.getOpacity());
        convexObject.setVisible(mapObject.isVisible());
        convexObject.getProperties().putAll(mapObject.getProperties());
        fixtures[i] = createFixture(convexObject, body);
    }

    return fixtures;
}