Example usage for com.badlogic.gdx.physics.box2d Fixture setUserData

List of usage examples for com.badlogic.gdx.physics.box2d Fixture setUserData

Introduction

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

Prototype

public void setUserData(Object userData) 

Source Link

Document

Sets custom user data.

Usage

From source file:com.barconr.games.marblegame.Physics2D.java

License:Apache License

public void createFixtures(TiledMap tiledmap) {
    int layerHeight = 0, layerWidth = 0;
    float tileWidth = 0, tileHeight = 0;

    ballsListener = new BallContactListener();

    // Load the Tiled map layer and store some relevant variables
    TiledMapTileLayer tilelayer = (TiledMapTileLayer) (tiledmap.getLayers().get(0));
    layerHeight = tilelayer.getHeight();
    layerWidth = tilelayer.getWidth();/*from  www . jav  a2s.c  om*/

    maze = new Maze(layerWidth, layerHeight);

    tileHeight = tilelayer.getTileHeight();
    tileWidth = tilelayer.getTileWidth();

    System.out.println("Layer height (tiles) = " + layerHeight + " Layer width (tiles) = " + layerWidth
            + " Tile height = " + tileHeight + "tile width = " + tileWidth);
    System.out.println("Tile count = " + tilelayer.getObjects().getCount());
    System.out.println("layer height pixels = " + (layerHeight * tileHeight) + "LAYER WIDTH PIXELS : "
            + (layerWidth * tileWidth));

    //Create the box2d world
    world = new World(new Vector2(0, -9), true);
    world.setContactListener(ballsListener);

    // Loop through the grid reference
    for (int y_pos = 0; y_pos < layerHeight; y_pos++) {

        for (int x_pos = 0; x_pos < layerWidth; x_pos++) {

            boolean impassibleBlock = tilelayer.getCell(x_pos, layerHeight - y_pos - 1).getTile()
                    .getProperties().containsKey("block");

            // If the tile square contains the reference "start"
            // Store this as the start position
            if (tilelayer.getCell(x_pos, layerHeight - y_pos - 1).getTile().getProperties()
                    .containsKey("start")) {
                if (startPosition == null) {
                    System.out.println("x:" + x_pos * tileWidth + " y:" + y_pos * tileHeight);
                    startPosition = new Vector2(x_pos * tileWidth * Assets.METERS_PER_PIXEL,
                            (50 - y_pos) * tileHeight * Assets.METERS_PER_PIXEL);

                }

            }

            //Create a fixture for the end position
            if (tilelayer.getCell(x_pos, layerHeight - y_pos - 1).getTile().getProperties()
                    .containsKey("end")) {
                //Draw box for fixture that is impassible
                PolygonShape squareShape = new PolygonShape();

                BodyDef squareBodyDef = new BodyDef();

                squareBodyDef.type = BodyType.StaticBody; //Static body which won't move
                //Box position
                squareBodyDef.position.set(new Vector2((x_pos * Assets.METERS_PER_PIXEL * tileWidth),
                        (layerHeight - y_pos - 1) * Assets.METERS_PER_PIXEL * tileHeight));
                //Correction for fact Box2Ds squares are half width/height from center point
                squareBodyDef.position.add(tileWidth / 2 * Assets.METERS_PER_PIXEL,
                        tileHeight / 2 * Assets.METERS_PER_PIXEL);

                Body squareBody = world.createBody(squareBodyDef);

                squareShape.setAsBox(tileWidth / 2 * Assets.METERS_PER_PIXEL,
                        tileHeight / 2 * Assets.METERS_PER_PIXEL);
                FixtureDef fixDefSquare = new FixtureDef();

                fixDefSquare.shape = squareShape;
                fixDefSquare.isSensor = true;

                fixDefSquare.density = 0.1f;
                fixDefSquare.restitution = 0.3f;

                Fixture endFix = squareBody.createFixture(fixDefSquare);
                endFix.setSensor(true);
                endFix.setUserData("exit");
            }

            if (impassibleBlock) {

                //Draw box for fixture that blocks

                maze.setMazeUnit(new MazeUnit("block"), x_pos, y_pos);
                //System.out.print("@");      // Draw ascii map in stdout

            } else {
                maze.setMazeUnit(new MazeUnit("passage"), x_pos, y_pos);
            }

        }
        //System.out.println();
    }

    // The players ball
    playerBallBodyDef = new BodyDef();
    playerBallBodyDef.type = BodyType.DynamicBody;

    if (startPosition == null) {
        playerBallBodyDef.position.set(3f, 3f);

    } else {
        playerBallBodyDef.position.set(startPosition.x, startPosition.y);
    }
    playerBallBodyDef.allowSleep = false;

    ballCircleBody = world.createBody(playerBallBodyDef);

    dynamicCircle = new CircleShape();
    dynamicCircle.setRadius(8 / Assets.PIXELS_PER_METER);

    FixtureDef ballFixtureDef = new FixtureDef();
    ballFixtureDef.shape = dynamicCircle;
    ballFixtureDef.density = 0.1f;
    ballFixtureDef.friction = 1f;
    //ballFixtureDef.

    ballFixtureDef.restitution = 0.5f;
    //ballCircleBody.setUserData("ball");
    Fixture fx = ballCircleBody.createFixture(ballFixtureDef);
    fx.setUserData("ball");

    maze.removeExtraBoxes();
    /*
    PolygonShape squareShape = new PolygonShape();
            
    */

    for (int i = 0; i < maze.width; i++) {
        for (int j = 0; j < maze.height; j++) {
            if (maze.mazeUnits[j][i].getType().equals("block")) {
                BodyDef squareBodyDef = new BodyDef();
                PolygonShape squareShape = new PolygonShape();
                squareBodyDef.type = BodyType.StaticBody; //Static body which won't move
                //Box position
                squareBodyDef.position.set(new Vector2((j * Assets.METERS_PER_PIXEL * tileWidth),
                        (layerHeight - i - 1) * Assets.METERS_PER_PIXEL * tileHeight));
                //Correction for fact Box2Ds squares are half width/height from center point
                squareBodyDef.position.add(tileWidth / 2 * Assets.METERS_PER_PIXEL,
                        tileHeight / 2 * Assets.METERS_PER_PIXEL);

                Body squareBody = world.createBody(squareBodyDef);
                //Size of box
                squareShape.setAsBox(tileWidth / 2 * Assets.METERS_PER_PIXEL,
                        tileHeight / 2 * Assets.METERS_PER_PIXEL);
                FixtureDef fixDefSquare = new FixtureDef();
                fixDefSquare.shape = squareShape;
                fixDefSquare.density = 0.1f;
                fixDefSquare.restitution = 0.3f;
                squareBody.createFixture(fixDefSquare);
            }
        }
    }

}

From source file:com.dgzt.core.button.AbstractButton.java

License:Open Source License

/**
 * Create the box2D body.//from w ww.j  av a 2s. c  om
 * 
 * @param box2DWorld - The box2D world.
 * @return - The box2D body.
 */
private Body createBox2DBody(final World box2DWorld) {
    BodyDef bodyDef = new BodyDef();
    bodyDef.type = BodyType.DynamicBody;
    bodyDef.position.set(box2DX, box2DY);

    Body body = box2DWorld.createBody(bodyDef);

    CircleShape circle = new CircleShape();
    circle.setRadius(box2DRadius);

    FixtureDef fixtureDef = new FixtureDef();
    fixtureDef.shape = circle;
    fixtureDef.density = FIXTURE_DEFINITION_DENSITY;
    fixtureDef.friction = FIXTURE_DEFINITION_FRICTION;
    fixtureDef.restitution = FIXTURE_DEFINITION_RESTITUTION;

    fixtureDef.filter.categoryBits = getCategoryBits();
    fixtureDef.filter.maskBits = getMaskBits();

    final Fixture fixture = body.createFixture(fixtureDef);
    fixture.setUserData(this);

    circle.dispose();

    // The linear damping.
    body.setLinearDamping(BOX2D_BODY_LINEAR_DAMPING);

    return body;
}

From source file:com.dgzt.core.util.Box2DUtil.java

License:Open Source License

/**
 * Add box2D rectangle./*from w w  w . jav  a2s. co  m*/
 * 
 * @param box2DWorld - The world of the Box2D.
 * @param x - The x coordinate value.
 * @param y - The y coordinate value.
 * @param width - The width value.
 * @param height - The height value.
 * @param isSensor - Is the rectangle sensor?
 * @param userData - The user data of fixture.
 * @param categoryBits - The category bits of filter.
 * @param maskBits - The mask bits of filter.
 */
private static void addRectangle(final World box2DWorld, final float x, final float y, final float width,
        final float height, final boolean isSensor, final Object userData, final short cateforyBits,
        final short maskBits) {
    final BodyDef bodyDef = new BodyDef();
    bodyDef.position.set(x + width / 2, y + height / 2);

    final Body body = box2DWorld.createBody(bodyDef);

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

    final FixtureDef fixtureDef = new FixtureDef();
    fixtureDef.shape = shape;
    fixtureDef.density = 1.0f;
    fixtureDef.isSensor = isSensor;

    fixtureDef.filter.categoryBits = cateforyBits;
    fixtureDef.filter.maskBits = maskBits;

    final Fixture fixture = body.createFixture(fixtureDef);
    fixture.setUserData(userData);
}

From source file:com.dongbat.game.util.PhysicsUtil.java

/**
 * Create a box2d Body/* w  w w.  ja v  a2  s .c  o  m*/
 *
 * @param physicsWorld box2d world
 * @param position body position
 * @param radius body radius
 * @param e set user data to entity e
 * @return Body that was just created
 */
public static Body createBody(World physicsWorld, Vector2 position, float radius, Entity e) {

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

    Body body = physicsWorld.createBody(bodyDef);
    body.setUserData(UuidUtil.getUuid(e));

    CircleShape circle = new CircleShape();
    circle.setRadius(radius);

    //collision fixture
    FixtureDef fixtureDef = new FixtureDef();
    fixtureDef.shape = circle;
    fixtureDef.density = 1;
    fixtureDef.isSensor = true;
    //    fixtureDef.filter.maskBits = 1;
    //    fixtureDef.filter.categoryBits = 2;
    Fixture collisionFixture = body.createFixture(fixtureDef);
    collisionFixture.setUserData("collision");

    CircleShape circle2 = new CircleShape();
    circle2.setRadius(15);
    // detection fixture
    FixtureDef fixtureDef2 = new FixtureDef();
    fixtureDef2.shape = circle2;
    fixtureDef2.density = 0;
    fixtureDef2.isSensor = true;
    //    fixtureDef.filter.maskBits = 1;
    //    fixtureDef.filter.categoryBits = 2;
    //    Fixture detectionFixture = body.createFixture(fixtureDef2);
    //    detectionFixture.setUserData("detection");

    circle.dispose();
    circle2.dispose();

    return body;
}

From source file:com.hatstick.fireman.physics.Box2DPhysicsWorld.java

License:Apache License

private Fixture createPhysicsObject(Rectangle bounds, ModelType type, Integer id) {

    UserData userData = new UserData(numEnterPoints, type, null);
    CircleShape objectPoly = new CircleShape();
    objectPoly.setRadius(bounds.width / 2);

    BodyDef enemyBodyDef = new BodyDef();
    enemyBodyDef.type = BodyType.DynamicBody;
    enemyBodyDef.position.x = bounds.x;/*from w w  w . java 2  s.c om*/
    enemyBodyDef.position.y = bounds.y;
    Body objectBody = world.createBody(enemyBodyDef);
    FixtureDef objectFixtureDef = new FixtureDef();
    objectFixtureDef.shape = objectPoly;

    //   objectBody.setUserData(userData);
    objectFixtureDef.restitution = .025f;
    Fixture fixture = objectBody.createFixture(objectFixtureDef);
    fixture.setUserData(userData);
    objectBody.setLinearDamping(2f);
    objectBody.setGravityScale(.4f);
    objectBody.setFixedRotation(true);
    objectPoly.dispose();
    numEnterPoints++;

    //add a sensor on the bottom to check if touching ground (for jumping)
    PolygonShape polygonShape = new PolygonShape();
    polygonShape.setAsBox(bounds.width / 3, bounds.height / 8, new Vector2(0, -bounds.height / 2), 0);
    objectFixtureDef = new FixtureDef();
    objectFixtureDef.shape = polygonShape;
    objectFixtureDef.isSensor = true;
    Fixture footSensorFixture = objectBody.createFixture(objectFixtureDef);
    footSensorFixture.setUserData(new UserData(numEnterPoints, ModelType.FOOT_SENSOR, id));

    //add a sensor on left side to check if touching wall (for grappling)
    PolygonShape polygonShape2 = new PolygonShape();
    polygonShape2.setAsBox(bounds.width / 8, bounds.height / 3, new Vector2(-bounds.width / 2, 0), 0);
    objectFixtureDef = new FixtureDef();
    objectFixtureDef.shape = polygonShape2;
    objectFixtureDef.isSensor = true;
    Fixture leftSideSensorFixture = objectBody.createFixture(objectFixtureDef);
    leftSideSensorFixture.setUserData(new UserData(numEnterPoints, ModelType.LEFT_SIDE_SENSOR, id));

    //add a sensor on right side to check if touching wall (for grappling)
    polygonShape2.setAsBox(bounds.width / 8, bounds.height / 3, new Vector2(bounds.width / 2, 0), 0);
    objectFixtureDef = new FixtureDef();
    objectFixtureDef.shape = polygonShape2;
    objectFixtureDef.isSensor = true;
    Fixture rightSideSensorFixture = objectBody.createFixture(objectFixtureDef);
    rightSideSensorFixture.setUserData(new UserData(numEnterPoints, ModelType.RIGHT_SIDE_SENSOR, id));

    return fixture;
}

From source file:com.hatstick.fireman.physics.Box2DPhysicsWorld.java

License:Apache License

private void createDestruction() {
    UserData userData = new UserData(numEnterPoints, ModelType.WALL, null);
    PolygonShape brickPoly = new PolygonShape();
    brickPoly.setAsBox(0.5f, 0.5f);//from   www .  ja v  a  2s . c  o  m

    BodyDef brickBodyDef = new BodyDef();
    brickBodyDef.type = BodyType.DynamicBody;
    brickBodyDef.position.x = 2;
    brickBodyDef.position.y = 2;
    Body brickBody = world.createBody(brickBodyDef);

    FixtureDef brickFixtureDef = new FixtureDef();
    brickFixtureDef.shape = brickPoly;
    // For now, it seems the best way to tell our renderer what our 
    // object is through userData...
    //brickBody.setUserData(userData);
    Fixture fixture = brickBody.createFixture(brickFixtureDef);
    fixture.setUserData(userData);
    brickPoly.dispose();
    numEnterPoints++;

    xEngine.boom(new Vector2(2.1f, 2.1f), brickBody, this);
}

From source file:com.hatstick.fireman.physics.Box2DPhysicsWorld.java

License:Apache License

private void createBoxes(Rectangle bounds) {

    UserData userData = new UserData(numEnterPoints, ModelType.WALL, null);
    PolygonShape brickPoly = new PolygonShape();
    brickPoly.setAsBox(bounds.width / 2, bounds.height / 2);

    BodyDef brickBodyDef = new BodyDef();
    brickBodyDef.type = BodyType.StaticBody;
    brickBodyDef.position.x = bounds.x;// w w  w  .  j ava2  s.c  o m
    brickBodyDef.position.y = bounds.y;
    Body brickBody = world.createBody(brickBodyDef);

    FixtureDef brickFixtureDef = new FixtureDef();
    brickFixtureDef.shape = brickPoly;
    // For now, it seems the best way to tell our renderer what our 
    // object is through userData...
    //brickBody.setUserData(userData);
    Fixture fixture = brickBody.createFixture(brickFixtureDef);
    fixture.setUserData(userData);
    brickPoly.dispose();
    numEnterPoints++;

}

From source file:com.rubentxu.juegos.core.utils.dermetfan.box2d.Box2DMapObjectParser.java

License:Apache License

/**
 * creates a {@link Fixture} from a {@link MapObject}
 *
 * @param mapObject the {@link MapObject} to parse
 * @return the parsed {@link Fixture}//from   ww w. j av  a  2  s  .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 = 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.siondream.core.physics.PhysicsData.java

License:Apache License

public Body createBody(Object userData) {
    World world = Env.game.getWorld();//www  .  j  av  a2 s . co m
    Body body = world.createBody(bodyDef);
    body.setMassData(massData);
    body.setUserData(userData);

    for (int i = 0; i < fixtureDefs.size; ++i) {
        Fixture fixture = body.createFixture(fixtureDefs.get(i));
        fixture.setUserData(i);
    }

    return body;
}

From source file:com.siondream.libgdxjam.physics.PhysicsData.java

License:Apache License

public Body createBody(World world, Object userData) {
    Body body = world.createBody(bodyDef);
    body.setMassData(massData);//  w ww .  java2 s.co  m
    body.setUserData(userData);

    for (int i = 0; i < fixtureDefs.size; ++i) {
        Fixture fixture = body.createFixture(fixtureDefs.get(i));
        fixture.setUserData(i);
    }

    return body;
}