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

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

Introduction

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

Prototype

public void setUserData(Object userData) 

Source Link

Document

Set the user data

Usage

From source file:com.agateau.pixelwheels.racer.Vehicle.java

License:Open Source License

public WheelInfo addWheel(TextureRegion region, float x, float y, float angle) {
    WheelInfo info = new WheelInfo();
    info.wheel = new Wheel(mGameWorld, this, region, getX() + x, getY() + y, angle);
    mWheels.add(info);/*w w  w.j a va  2 s.  c o  m*/

    Body body = info.wheel.getBody();
    body.setUserData(mBody.getUserData());

    RevoluteJointDef jointDef = new RevoluteJointDef();
    // Call initialize() instead of defining bodies and anchors manually. Defining anchors manually
    // causes Box2D to move the car a bit while it solves the constraints defined by the joints
    jointDef.initialize(mBody, body, body.getPosition());
    jointDef.lowerAngle = 0;
    jointDef.upperAngle = 0;
    jointDef.enableLimit = true;
    info.joint = (RevoluteJoint) mGameWorld.getBox2DWorld().createJoint(jointDef);

    return info;
}

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.
 * //  w ww.  java 2  s  .com
 * @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.arkanoid.game.model.GameField.java

License:Apache License

public void removeBody(Body body) {
    step(1);//from  ww w .ja va2 s . co m
    if (!world.isLocked()) {
        if (body != null) {
            body.setUserData(null);
            //to prevent some obscure c assertion that happened randomly once in a blue moon
            final Array<JointEdge> list = body.getJointList();
            for (JointEdge edge : list) {
                world.destroyJoint(edge.joint);
            }
            // actual remove
            this.world.destroyBody(body);
        }
    }
}

From source file:com.badlogic.gdx.ai.tests.steer.box2d.Box2dSteeringEntity.java

License:Apache License

public Box2dSteeringEntity(TextureRegion region, Body body, boolean independentFacing, float boundingRadius) {
    this.region = region;
    this.body = body;
    this.independentFacing = independentFacing;
    this.boundingRadius = boundingRadius;
    this.tagged = false;

    body.setUserData(this);
}

From source file:com.badlogic.gdx.tests.box2d.VerticalStack.java

License:Apache License

@Override
protected void createWorld(World world) {
    {/*from  w w w.  j  a  v  a2 s.co  m*/
        BodyDef bd = new BodyDef();
        Body ground = world.createBody(bd);

        EdgeShape shape = new EdgeShape();
        shape.set(new Vector2(-40, 0), new Vector2(40, 0));
        ground.createFixture(shape, 0.0f);

        shape.set(new Vector2(20, 0), new Vector2(20, 20));
        ground.createFixture(shape, 0);
        shape.dispose();
    }

    float xs[] = { 0, -10, -5, 5, 10 };

    for (int j = 0; j < e_columnCount; j++) {
        PolygonShape shape = new PolygonShape();
        shape.setAsBox(0.5f, 0.5f);

        FixtureDef fd = new FixtureDef();
        fd.shape = shape;
        fd.density = 1.0f;
        fd.friction = 0.3f;

        for (int i = 0; i < e_rowCount; i++) {
            BodyDef bd = new BodyDef();
            bd.type = BodyType.DynamicBody;

            int n = j * e_rowCount + i;
            m_indices[n] = n;

            float x = 0;
            bd.position.set(xs[j] + x, 0.752f + 1.54f * i);
            Body body = world.createBody(bd);
            body.setUserData(n);

            m_bodies[n] = body;
            body.createFixture(fd);
        }

        shape.dispose();
    }

    m_bullet = null;
}

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

/**
 * Create a box2d Body/* w ww  . ja va 2s .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.gamestudio24.martianrun.utils.WorldUtils.java

License:Apache License

public static Body createGround(World world) {
    BodyDef bodyDef = new BodyDef();
    bodyDef.position.set(new Vector2(Constants.GROUND_X, Constants.GROUND_Y));
    Body body = world.createBody(bodyDef);
    PolygonShape shape = new PolygonShape();
    shape.setAsBox(Constants.GROUND_WIDTH / 2, Constants.GROUND_HEIGHT / 2);
    body.createFixture(shape, Constants.GROUND_DENSITY);
    body.setUserData(new GroundUserData(Constants.GROUND_WIDTH, Constants.GROUND_HEIGHT));
    shape.dispose();//w  w  w . j a  v a 2 s.c  o  m
    return body;
}

From source file:com.gamestudio24.martianrun.utils.WorldUtils.java

License:Apache License

public static Body createRunner(World world) {
    BodyDef bodyDef = new BodyDef();
    bodyDef.type = BodyDef.BodyType.DynamicBody;
    bodyDef.position.set(new Vector2(Constants.RUNNER_X, Constants.RUNNER_Y));
    PolygonShape shape = new PolygonShape();
    shape.setAsBox(Constants.RUNNER_WIDTH / 2, Constants.RUNNER_HEIGHT / 2);
    Body body = world.createBody(bodyDef);
    body.setGravityScale(Constants.RUNNER_GRAVITY_SCALE);
    body.createFixture(shape, Constants.RUNNER_DENSITY);
    body.resetMassData();//  ww w  .  j  a va  2 s  .co m
    body.setUserData(new RunnerUserData(Constants.RUNNER_WIDTH, Constants.RUNNER_HEIGHT));
    shape.dispose();
    return body;
}

From source file:com.gamestudio24.martianrun.utils.WorldUtils.java

License:Apache License

public static Body createEnemy(World world) {
    EnemyType enemyType = RandomUtils.getRandomEnemyType();
    BodyDef bodyDef = new BodyDef();
    bodyDef.type = BodyDef.BodyType.KinematicBody;
    bodyDef.position.set(new Vector2(enemyType.getX(), enemyType.getY()));
    PolygonShape shape = new PolygonShape();
    shape.setAsBox(enemyType.getWidth() / 2, enemyType.getHeight() / 2);
    Body body = world.createBody(bodyDef);
    body.createFixture(shape, enemyType.getDensity());
    body.resetMassData();//from  ww  w. j  ava  2  s.  co m
    EnemyUserData userData = new EnemyUserData(enemyType.getWidth(), enemyType.getHeight(),
            enemyType.getAnimationAssetId());
    body.setUserData(userData);
    shape.dispose();
    return body;
}

From source file:com.github.mkjensen.breakall.actor.Box2DActor.java

License:Apache License

private Body setupBody() {
    Body body = createBody(world);
    body.setActive(false);
    body.setUserData(this);
    return body;
}