Example usage for com.badlogic.gdx.physics.box2d CircleShape setPosition

List of usage examples for com.badlogic.gdx.physics.box2d CircleShape setPosition

Introduction

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

Prototype

public void setPosition(Vector2 position) 

Source Link

Document

Sets the position of the shape

Usage

From source file:Tabox2D.java

License:Open Source License

/**
 * Combines different tabodies in a single one.<br/>
 * This is useful to have a body with different fixtures in an easy way
 * @param tabodyArray Array of tabodies to combine
 * @return A new Tabody//w  w w  .j ava  2  s . c o m
 */
public Tabody combine(String type, Tabody... tabodyArray) {
    if (tabodyArray.length > 0) {

        Tabody newTabody = new Tabody();

        BodyDef bodyDef = new BodyDef();
        setType(bodyDef, type);

        //List<Vector2> centers = new ArrayList<Vector2>();

        //AABB center of combines bodies:
        List<Vector2> ptsCombined = new ArrayList<Vector2>();
        for (int i = 0; i < tabodyArray.length; i++) {
            //centers.add(tabodyArray[i].body.getWorldCenter());
            Tabody t = tabodyArray[i];
            for (Fixture f : t.body.getFixtureList()) {
                if (f.getShape() instanceof CircleShape) {
                    CircleShape cS = (CircleShape) f.getShape();
                    // top-left and bottom-right of circle bounds:
                    ptsCombined.add(new Vector2(cS.getPosition().x - cS.getRadius(),
                            cS.getPosition().y + cS.getRadius()));
                    ptsCombined.add(new Vector2(cS.getPosition().x + cS.getRadius(),
                            cS.getPosition().y - cS.getRadius()));
                } else if (f.getShape() instanceof PolygonShape) {
                    PolygonShape pS = (PolygonShape) f.getShape();
                    for (int n = 0; n < pS.getVertexCount(); n++) {
                        Vector2 tmp = new Vector2();
                        pS.getVertex(n, tmp);
                        ptsCombined.add(
                                new Vector2(t.body.getPosition().x + tmp.x, t.body.getPosition().y + tmp.y));
                    }
                }
            }
        }

        Rectangle rectangle = boundingBoxOf(ptsCombined);

        bodyDef.position.set(rectangle.x + rectangle.width / 2, rectangle.y + rectangle.height / 2);

        newTabody.w = rectangle.width * meterSize;
        newTabody.h = rectangle.height * meterSize;
        newTabody.body = world.createBody(bodyDef);

        for (int i = 0; i < tabodyArray.length; i++) {

            Tabody t = tabodyArray[i];

            for (Fixture f : t.body.getFixtureList()) {
                FixtureDef fixtureDef = new FixtureDef();

                fixtureDef.density = f.getDensity();
                fixtureDef.friction = f.getFriction();
                fixtureDef.restitution = f.getRestitution();
                // Delta X and Y for translating the shapes:
                float dx = t.body.getWorldCenter().x - bodyDef.position.x;
                float dy = t.body.getWorldCenter().y - bodyDef.position.y;
                if (f.getShape() instanceof CircleShape) {

                    CircleShape circleShape = (CircleShape) f.getShape();
                    circleShape.setPosition(
                            new Vector2(circleShape.getPosition().x + dx, circleShape.getPosition().y + dy));
                    fixtureDef.shape = circleShape;

                } else if (f.getShape() instanceof PolygonShape) {

                    PolygonShape polygonShape = (PolygonShape) f.getShape();

                    float[] pts = new float[polygonShape.getVertexCount() * 2];
                    int vertexIndex = 0;
                    // delta X and delta Y respect to the main body:
                    dx = t.body.getPosition().x - bodyDef.position.x;
                    dy = t.body.getPosition().y - bodyDef.position.y;
                    for (int j = 0; j < pts.length - 1; j += 2) {
                        Vector2 tmp = new Vector2();
                        polygonShape.getVertex(vertexIndex, tmp);
                        pts[j] = tmp.x + dx;
                        pts[j + 1] = tmp.y + dy;
                        vertexIndex++;
                    }
                    polygonShape.set(pts);
                    fixtureDef.shape = polygonShape;

                } else if (f.getShape() instanceof EdgeShape) {
                    EdgeShape edgeShape = (EdgeShape) f.getShape();
                    fixtureDef.shape = edgeShape;
                }

                newTabody.body.createFixture(fixtureDef);
            }
        }

        // Destroy:
        for (int i = 0; i < tabodyArray.length; i++) {
            world.destroyBody(tabodyArray[i].body);
            tabodies.remove(tabodyArray[i]);
        }

        // Add new Tabody:
        tabodies.add(newTabody);
        return newTabody;
    } else {
        System.err.println("No tabodies specified in Tabox2D.combine()");
        return null;
    }
}

From source file:com.laex.cg2d.render.impl.EntityManager.java

License:Open Source License

/**
 * Creates the entity collision shape./*from  w ww. j  a v  a2s  .c o  m*/
 * 
 * @param shape
 *          the shape
 * @param entity
 *          the entity
 * @param ea
 *          the ea
 * @param bodyDef
 *          the body def
 * @param fixDef
 *          the fix def
 * @param b
 *          the b
 */
public void createEntityCollisionShape(CGShape shape, CGEntity entity, CGEntityAnimation ea, BodyDef bodyDef,
        FixtureDef fixDef, Body b) {

    CGEntityCollisionType shapeType = ea.getCollisionType();
    PolygonShape polyShape = new PolygonShape();
    Vector2[] va = null;

    // check if shape type is NONE. NONE shape type means that this entity
    // has no collision parameters defined.
    // We simple ignore this and do not create any shape collision for this
    // object
    if (shapeType == CGEntityCollisionType.NONE) {
        // /set empty origin vertex so that other codes do not have to check null
        // pointer exception on its part
        shapeToAnimationOriginMap.put(shape, new Vector3(0, 0, 0));
        return;
    }

    switch (shapeType) {
    case BOX:
        va = normalizeVertices(ea.getVerticesList(), shape.getBounds().getHeight());
        polyShape.set(va);

        shapeToAnimationOriginMap.put(shape, new Vector3(0, 0, 0));

        fixDef.shape = polyShape;
        b.createFixture(fixDef);
        break;

    case CIRCLE: {
        manipulator.world().destroyBody(b);

        CircleShape circShape = new CircleShape();

        /* Decode x,y, width, height of collision shape from the vertices */
        CGVector2 v1 = ea.getVertices(0);
        CGVector2 v2 = ea.getVertices(2);

        Rectangle r = new Rectangle(v1.getX(), v1.getY(), v2.getX(), v2.getY());
        r.width = r.width - r.x;
        r.height = r.height - r.y;

        // this radius is calculated for circle's collision shape data not
        // the sprite width/height data
        float radius = CircleBody.calculateRadiusOfCircleShape(r.width, manipulator.ptmRatio());

        Vector2 cpos = new Vector2(r.x, r.y);
        cpos.y = shape.getBounds().getHeight() - r.height - r.y;
        cpos = ScreenToWorld.inst(manipulator.model()).screenToWorld(cpos);

        /* Calculate origin */
        int x = (int) r.x;
        int y = (int) r.y;
        int w = (int) r.width;
        int h = (int) r.height;

        /*
         * ptmRatioSquared should be casted to integer to avoid floating point
         * calculation division. If not, the orirgin will actully diverge and will
         * be clearly seen in the rotation of the circle shape
         */
        int ptmRatioSquared = (int) (manipulator.ptmRatio() * manipulator.ptmRatio());
        float ox = (x + w) / (ptmRatioSquared) + radius;
        float oy = (y + h) / (ptmRatioSquared) + radius;
        /* End origin calculatio */

        b = manipulator.world().createBody(bodyDef);

        circShape.setRadius(radius);
        circShape.setPosition(cpos);

        shapeToAnimationOriginMap.put(shape, new Vector3(ox, oy, radius));

        fixDef.shape = circShape;
        b.createFixture(fixDef);
    }
        break;

    case CUSTOM:
        BodyEditorLoader bel = new BodyEditorLoader(
                Gdx.files.absolute(ea.getFixtureFile().getResourceFileAbsolute()));
        // scale = image width or image height / ptmRatio
        /*
         * bodyScale: Consider this: scale is a factor which scales the vertices
         * created by Physcis Editor. This scale is not equals to ptmRatio or
         * scaleFactor. bodyScale is the width or height of the image / ptmRatio
         * imageWidth = 32, scale = imageWidth / ptmRatio = 32 / 16 = 2 imageWidth
         * = 32, scale = imageWidth / ptmRatio = 32 / 32 = 1
         */
        float bodyScale = (shape.getBounds().getWidth() / manipulator.ptmRatio());
        bel.attachFixture(b, ea.getAnimationName(), fixDef, bodyScale);
        Vector2 or = bel.getOrigin(ea.getAnimationName(), bodyScale);
        shapeToAnimationOriginMap.put(shape, new Vector3(or.x, or.y, 0));
        break;

    case NONE:
    default:
        break;
    }

}

From source file:com.me.main.startgame.java

License:Apache License

private Body createPlayer() {
    BodyDef def = new BodyDef();
    def.type = BodyType.DynamicBody;//from   w  w  w. ja v a  2 s. c o m

    PolygonShape poly = new PolygonShape();
    poly.setAsBox(0.2f, 0.3f);

    FixtureDef sqrdef = new FixtureDef();
    sqrdef.shape = poly;
    sqrdef.density = 1;

    CircleShape circle = new CircleShape();
    circle.setRadius(0.2f);
    circle.setPosition(new Vector2(0, -0.25f));

    FixtureDef circledef = new FixtureDef();
    circledef.shape = circle;
    circledef.density = 1;

    Body box = world.createBody(def);
    scene.setCustom(box, "tipo", TIPOPLAYER);
    box.setBullet(true);
    playerPhysicsFixture = box.createFixture(sqrdef);
    playerSensorFixture = box.createFixture(circledef);

    return box;
}

From source file:com.mygdx.game.steeringTest2.java

public static Box2dSteeringEntity createSteeringEntity(World world, TextureRegion region,
        boolean independentFacing, int posX, int posY) {

    CircleShape circleChape = new CircleShape();
    circleChape.setPosition(new Vector2());
    int radiusInPixels = (int) ((region.getRegionWidth() + region.getRegionHeight()) / 4f);
    circleChape.setRadius(radiusInPixels / PPM);

    BodyDef characterBodyDef = new BodyDef();
    characterBodyDef.position.set((posX) / PPM, (posY) / PPM);
    characterBodyDef.type = BodyType.DynamicBody;
    Body characterBody = world.createBody(characterBodyDef);

    FixtureDef charFixtureDef = new FixtureDef();
    charFixtureDef.density = 1;/*w w w  . java 2s. c  om*/
    charFixtureDef.shape = circleChape;
    charFixtureDef.filter.groupIndex = 0;
    characterBody.createFixture(charFixtureDef);

    circleChape.dispose();

    return new Box2dSteeringEntity(region, characterBody, independentFacing, radiusInPixels / PPM);
}

From source file:com.nebula2d.components.Circle.java

License:Open Source License

@Override
protected Shape getShape(Transform transform) {
    CircleShape circleShape = new CircleShape();
    circleShape.setPosition(transform.getPosition());
    circleShape.setRadius(radius);/*www.j  av a2 s  .  c o m*/

    return circleShape;
}

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

License:Open Source License

private Shape getCircle(CircleMapObject circleObject) {
    Circle circle = circleObject.getCircle();
    CircleShape circleShape = new CircleShape();
    circleShape.setRadius(circle.radius / units);
    circleShape.setPosition(new Vector2(circle.x / units, circle.y / units));
    return circleShape;
}

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

License:Apache License

private Shape loadShape(JsonValue root) {
    Shape shape = null;//from   ww  w. j  ava 2 s .co  m
    JsonValue shapeValue = root.get("shape");

    if (shapeValue == null) {
        return shape;
    }

    String type = shapeValue.getString("type");

    float x = shapeValue.getFloat("centerX", 0.0f);
    float y = shapeValue.getFloat("centerY", 0.0f);

    if (type.equals("circle")) {
        logger.info("loading cicle shape");
        CircleShape circle = new CircleShape();
        circle.setPosition(new Vector2(x, y));
        circle.setRadius(shapeValue.getFloat("radius", 1.0f));
        shape = circle;
    } else if (type.equals("polygon")) {
        logger.info("loading polygon shape");
        PolygonShape polygon = new PolygonShape();
        polygon.setAsBox(shapeValue.getFloat("width", 1.0f), shapeValue.getFloat("height", 1.0f),
                new Vector2(x, y), 0.0f);
        shape = polygon;
    } else {
        logger.error("shape unknown " + type);
    }

    return shape;
}

From source file:com.stercore.code.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) {
    if ((mapObject = listener.createFixture(mapObject)) == null)
        return null;

    String orientation = findProperty(aliases.orientation, aliases.orthogonal, heritage, mapProperties,
            layerProperties, mapObject.getProperties());
    transform(mat4, orientation);//from  w w  w .j a va 2  s .c  o m

    Shape shape = null;
    if (mapObject instanceof RectangleMapObject) {
        Rectangle rectangle = ((RectangleMapObject) mapObject).getRectangle();
        vec3.set(rectangle.x, rectangle.y, 0);
        vec3.mul(mat4);
        float x = vec3.x, y = vec3.y, width, height;
        if (!orientation.equals(aliases.staggered)) {
            vec3.set(rectangle.width, rectangle.height, 0).mul(mat4);
            width = vec3.x;
            height = vec3.y;
        } else {
            width = rectangle.width * unitScale;
            height = rectangle.height * unitScale;
        }
        ((PolygonShape) (shape = new PolygonShape())).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 || mapObject instanceof PolylineMapObject) {
        FloatArray vertices = Pools.obtain(FloatArray.class);
        vertices.clear();
        vertices.addAll(mapObject instanceof PolygonMapObject
                ? ((PolygonMapObject) mapObject).getPolygon().getTransformedVertices()
                : ((PolylineMapObject) mapObject).getPolyline().getTransformedVertices());
        for (int ix = 0, iy = 1; iy < vertices.size; ix += 2, iy += 2) {
            vec3.set(vertices.get(ix), vertices.get(iy), 0);
            vec3.mul(mat4);
            vertices.set(ix, vec3.x - body.getPosition().x);
            vertices.set(iy, vec3.y - body.getPosition().y);
        }
        if (mapObject instanceof PolygonMapObject)
            ((PolygonShape) (shape = new PolygonShape())).set(vertices.items, 0, vertices.size);
        else if (vertices.size == 4)
            ((EdgeShape) (shape = new EdgeShape())).set(vertices.get(0), vertices.get(1), vertices.get(2),
                    vertices.get(3));
        else {
            vertices.shrink();
            ((ChainShape) (shape = new ChainShape())).createChain(vertices.items);
        }
        Pools.free(vertices);
    } else if (mapObject instanceof CircleMapObject || mapObject instanceof EllipseMapObject) {
        if (mapObject instanceof CircleMapObject) {
            Circle circle = ((CircleMapObject) mapObject).getCircle();
            vec3.set(circle.x, circle.y, circle.radius);
        } else {
            Ellipse ellipse = ((EllipseMapObject) mapObject).getEllipse();
            if (ellipse.width != ellipse.height)
                throw new IllegalArgumentException("Cannot parse " + mapObject.getName() + " because "
                        + ClassReflection.getSimpleName(mapObject.getClass())
                        + "s that are not circles are not supported");
            vec3.set(ellipse.x + ellipse.width / 2, ellipse.y + ellipse.height / 2, ellipse.width / 2);
        }
        vec3.mul(mat4);
        vec3.sub(body.getPosition().x, body.getPosition().y, 0);
        CircleShape circleShape = (CircleShape) (shape = new CircleShape());
        circleShape.setPosition(vec2.set(vec3.x, vec3.y));
        circleShape.setRadius(vec3.z);
    } else if (mapObject instanceof TextureMapObject)
        throw new IllegalArgumentException("Cannot parse " + mapObject.getName() + " because "
                + ClassReflection.getSimpleName(mapObject.getClass()) + "s are not supported");
    else
        assert false : mapObject + " is a not known subclass of " + MapObject.class.getName();

    MapProperties properties = mapObject.getProperties();

    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(findProperty(aliases.userData, fixture.getUserData(), heritage, mapProperties,
            layerProperties, properties));

    shape.dispose();

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

    return fixture;
}

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

License:Apache License

/** creates a deep copy of a {@link Shape}<br>
 *  <strong>Note: The {@link ChainShape#setPrevVertex(float, float) previous} and {@link ChainShape#setNextVertex(float, float) next} vertex of a {@link ChainShape} will not be copied since this is not possible due to the API.</strong>
 *  @param shape the {@link Shape} to copy
 *  @return a {@link Shape} exactly like the one passed in */
@SuppressWarnings("unchecked")
public static <T extends Shape> T clone(T shape) {
    T clone;/* w w w .  ja v  a 2  s.co  m*/
    switch (shape.getType()) {
    case Circle:
        CircleShape circleClone = (CircleShape) (clone = (T) new CircleShape());
        circleClone.setPosition(((CircleShape) shape).getPosition());
        break;
    case Polygon:
        PolygonShape polyClone = (PolygonShape) (clone = (T) new PolygonShape()), poly = (PolygonShape) shape;
        float[] vertices = new float[poly.getVertexCount()];
        for (int i = 0; i < vertices.length; i++) {
            poly.getVertex(i, vec2_0);
            vertices[i++] = vec2_0.x;
            vertices[i] = vec2_0.y;
        }
        polyClone.set(vertices);
        break;
    case Edge:
        EdgeShape edgeClone = (EdgeShape) (clone = (T) new EdgeShape()), edge = (EdgeShape) shape;
        edge.getVertex1(vec2_0);
        edge.getVertex2(vec2_1);
        edgeClone.set(vec2_0, vec2_1);
        break;
    case Chain:
        ChainShape chainClone = (ChainShape) (clone = (T) new ChainShape()), chain = (ChainShape) shape;
        vertices = new float[chain.getVertexCount()];
        for (int i = 0; i < vertices.length; i++) {
            chain.getVertex(i, vec2_0);
            vertices[i++] = vec2_0.x;
            vertices[i] = vec2_0.y;
        }
        if (chain.isLooped())
            chainClone.createLoop(GeometryUtils.toVector2Array(vertices));
        else
            chainClone.createChain(vertices);
        break;
    default:
        return null;
    }
    clone.setRadius(shape.getRadius());
    return clone;
}

From source file:com.strategames.engine.gameobject.types.Star.java

License:Open Source License

@Override
protected void setupBody(Body body) {
    float radius = getHalfWidth() * 0.7f;

    CircleShape circle = new CircleShape();
    circle.setRadius(radius);//from   w  w w .ja  v  a  2s  .  co  m
    circle.setPosition(new Vector2(getHalfWidth(), getHalfHeight()));
    Fixture fixture = body.createFixture(circle, 0.0f);
    fixture.setSensor(true);

    circle.dispose();
}