Java Code Examples for com.badlogic.gdx.physics.box2d.Body#createFixture()

The following examples show how to use com.badlogic.gdx.physics.box2d.Body#createFixture() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FixtureAtlas.java    From uracer-kotd with Apache License 2.0 6 votes vote down vote up
/** Creates and applies the fixtures defined in the editor. The name parameter is used to retrieve the shape from the loaded
 * binary file. Therefore, it _HAS_ to be the exact same name as the one that appeared. in the editor. <br/>
 * <br/>
 * 
 * WARNING: The body reference point is supposed to be the bottom left corner. As a result, calling "getPosition()" on the body
 * will return its bottom left corner. This is useful to draw a Sprite directly by setting its position to the body position. <br/>
 * <br/>
 * 
 * Also, saved shapes are normalized. Thus, you need to provide the desired width and height of your body for them to scale
 * according to your needs. <br/>
 * <br/>
 * 
 * Moreover, you can submit a custom FixtureDef object. Its parameters will be applied to every fixture applied to the body by
 * this method.
 * 
 * @param body A box2d Body, previously created.
 * @param name The name of the shape you want to load.
 * @param width The desired width of the body.
 * @param height The desired height of the body.
 * @param params Custom fixture parameters to apply. */
public void createFixtures (Body body, String name, float width, float height, FixtureDef params, Vector2 offset,
	Object userData) {
	BodyModel bm = bodyMap.get(name);
	if (bm == null) {
		Gdx.app.log("FixtureAtlas", name + " does not exist in the fixture list.");
	}

	Vector2[][] polygons = bm.getPolygons(width, height, offset);
	if (polygons == null) {
		Gdx.app.log("FixtureAtlas", name + " does not declare any polygon. "
			+ "Should not happen. Is your shape file corrupted ?");
	}

	for (Vector2[] polygon : polygons) {
		shape.set(polygon);
		FixtureDef fd = params == null ? DEFAULT_FIXTURE : params;
		fd.shape = shape;
		Fixture f = body.createFixture(fd);
		f.setUserData(userData);
	}
}
 
Example 2
Source File: Box2dLightTest.java    From box2dlights with Apache License 2.0 6 votes vote down vote up
private void createBoxes() {
	CircleShape ballShape = new CircleShape();
	ballShape.setRadius(RADIUS);

	FixtureDef def = new FixtureDef();
	def.restitution = 0.9f;
	def.friction = 0.01f;
	def.shape = ballShape;
	def.density = 1f;
	BodyDef boxBodyDef = new BodyDef();
	boxBodyDef.type = BodyType.DynamicBody;

	for (int i = 0; i < BALLSNUM; i++) {
		// Create the BodyDef, set a random position above the
		// ground and create a new body
		boxBodyDef.position.x = -20 + (float) (Math.random() * 40);
		boxBodyDef.position.y = 10 + (float) (Math.random() * 15);
		Body boxBody = world.createBody(boxBodyDef);
		boxBody.createFixture(def);
		balls.add(boxBody);
	}
	ballShape.dispose();
}
 
Example 3
Source File: Box2DFactory.java    From homescreenarcade with GNU General Public License v3.0 6 votes vote down vote up
/** Creates a circle object with the given position and radius. Resitution defaults to 0.6. */
public static Body createCircle(World world, float x, float y, float radius, boolean isStatic) {
    CircleShape sd = new CircleShape();
    sd.setRadius(radius);

    FixtureDef fdef = new FixtureDef();
    fdef.shape = sd;
    fdef.density = 1.0f;
    fdef.friction = 0.3f;
    fdef.restitution = 0.6f;

    BodyDef bd = new BodyDef();
    bd.allowSleep = true;
    bd.position.set(x, y);
    Body body = world.createBody(bd);
    body.createFixture(fdef);
    if (isStatic) {
        body.setType(BodyDef.BodyType.StaticBody);
    }
    else {
        body.setType(BodyDef.BodyType.DynamicBody);
    }
    return body;
}
 
Example 4
Source File: Box2DFactory.java    From homescreenarcade with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Creates a wall by constructing a rectangle whose corners are (xmin,ymin) and (xmax,ymax),
 * and rotating the box counterclockwise through the given angle, with specified restitution.
 */
public static Body createWall(World world, float xmin, float ymin, float xmax, float ymax,
        float angle, float restitution) {
    float cx = (xmin + xmax) / 2;
    float cy = (ymin + ymax) / 2;
    float hx = Math.abs((xmax - xmin) / 2);
    float hy = Math.abs((ymax - ymin) / 2);
    PolygonShape wallshape = new PolygonShape();
    // Don't set the angle here; instead call setTransform on the body below. This allows future
    // calls to setTransform to adjust the rotation as expected.
    wallshape.setAsBox(hx, hy, new Vector2(0f, 0f), 0f);

    FixtureDef fdef = new FixtureDef();
    fdef.shape = wallshape;
    fdef.density = 1.0f;
    if (restitution>0) fdef.restitution = restitution;

    BodyDef bd = new BodyDef();
    bd.position.set(cx, cy);
    Body wall = world.createBody(bd);
    wall.createFixture(fdef);
    wall.setType(BodyDef.BodyType.StaticBody);
    wall.setTransform(cx, cy, angle);
    return wall;
}
 
Example 5
Source File: WorldUtils.java    From martianrun with Apache License 2.0 6 votes vote down vote up
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();
    EnemyUserData userData = new EnemyUserData(enemyType.getWidth(), enemyType.getHeight(),
            enemyType.getAnimationAssetId());
    body.setUserData(userData);
    shape.dispose();
    return body;
}
 
Example 6
Source File: Box2dSteeringTest.java    From gdx-ai with Apache License 2.0 6 votes vote down vote up
public 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(Box2dSteeringTest.pixelsToMeters(radiusInPixels));

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

		FixtureDef charFixtureDef = new FixtureDef();
		charFixtureDef.density = 1;
		charFixtureDef.shape = circleChape;
		charFixtureDef.filter.groupIndex = 0;
		characterBody.createFixture(charFixtureDef);

		circleChape.dispose();

		return new Box2dSteeringEntity(region, characterBody, independentFacing, Box2dSteeringTest.pixelsToMeters(radiusInPixels));
	}
 
Example 7
Source File: ActorBuilder.java    From Bomberman_libGdx with MIT License 6 votes vote down vote up
public void createIndestructible(float x, float y, TextureAtlas tileTextureAtlas) {
    BodyDef bodyDef = new BodyDef();
    bodyDef.type = BodyDef.BodyType.StaticBody;
    bodyDef.position.set(x, y);

    Body body = b2dWorld.createBody(bodyDef);
    PolygonShape polygonShape = new PolygonShape();
    polygonShape.setAsBox(0.5f, 0.5f);
    FixtureDef fixtureDef = new FixtureDef();
    fixtureDef.shape = polygonShape;
    fixtureDef.filter.categoryBits = GameManager.INDESTRUCTIIBLE_BIT;
    fixtureDef.filter.maskBits = GameManager.PLAYER_BIT | GameManager.ENEMY_BIT | GameManager.BOMB_BIT;
    body.createFixture(fixtureDef);

    polygonShape.dispose();

    Renderer renderer = new Renderer(new TextureRegion(tileTextureAtlas.findRegion("indestructible"), 0, 0, 16, 16), 16 / GameManager.PPM, 16 / GameManager.PPM);
    renderer.setOrigin(16 / GameManager.PPM / 2, 16 / GameManager.PPM / 2);

    new EntityBuilder(world)
            .with(
                    new Transform(x, y, 1f, 1f, 0),
                    renderer
            )
            .build();
}
 
Example 8
Source File: BodyEditorLoader.java    From ninja-rabbit with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates and applies the fixtures defined in the editor. The name parameter is used to
 * retrieve the right fixture from the loaded file. <br/>
 * <br/>
 *
 * The body reference point (the red cross in the tool) is by default located at the bottom left
 * corner of the image. This reference point will be put right over the BodyDef position point.
 * Therefore, you should place this reference point carefully to let you place your body in your
 * world easily with its BodyDef.position point. Note that to draw an image at the position of
 * your body, you will need to know this reference point (see
 * {@link #getOrigin(java.lang.String, float)}. <br/>
 * <br/>
 *
 * Also, saved shapes are normalized. As shown in the tool, the width of the image is considered
 * to be always 1 meter. Thus, you need to provide a scale factor so the polygons get resized
 * according to your needs (not every body is 1 meter large in your game, I guess).
 *
 * @param body
 *            The Box2d body you want to attach the fixture to.
 * @param name
 *            The name of the fixture you want to load.
 * @param fd
 *            The fixture parameters to apply to the created body fixture.
 * @param scale
 *            The desired scale of the body. The default width is 1.
 */
public void attachFixture(final Body body, final String name, final FixtureDef fd, final float scale) {
	RigidBodyModel rbModel = model.rigidBodies.get(name);
	if (rbModel == null) {
		throw new RuntimeException("Name '" + name + "' was not found.");
	}

	Vector2 origin = vec.set(rbModel.origin).scl(scale);

	for (int i = 0, n = rbModel.polygons.size(); i < n; i++) {
		PolygonModel polygon = rbModel.polygons.get(i);
		Vector2[] vertices = polygon.buffer;

		for (int ii = 0, nn = vertices.length; ii < nn; ii++) {
			vertices[ii] = newVec().set(polygon.vertices.get(ii)).scl(scale);
			vertices[ii].sub(origin);
		}

		polygonShape.set(vertices);
		fd.shape = polygonShape;
		body.createFixture(fd);

		for (Vector2 vertice : vertices) {
			free(vertice);
		}
	}

	for (int i = 0, n = rbModel.circles.size(); i < n; i++) {
		CircleModel circle = rbModel.circles.get(i);
		Vector2 center = newVec().set(circle.center).scl(scale);
		float radius = circle.radius * scale;

		circleShape.setPosition(center);
		circleShape.setRadius(radius);
		fd.shape = circleShape;
		body.createFixture(fd);

		free(center);
	}
}
 
Example 9
Source File: Box2DFactory.java    From Codelabs with MIT License 5 votes vote down vote up
public static Body createBody(World world, BodyType bodyType,
		FixtureDef fixtureDef, Vector2 position) {
	BodyDef bodyDef = new BodyDef();
	bodyDef.type = bodyType;
	bodyDef.position.set(position);

	Body body = world.createBody(bodyDef);
	body.createFixture(fixtureDef);

	fixtureDef.shape.dispose();

	return body;
}
 
Example 10
Source File: WorldUtils.java    From martianrun with Apache License 2.0 5 votes vote down vote up
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();
    body.setUserData(new RunnerUserData(Constants.RUNNER_WIDTH, Constants.RUNNER_HEIGHT));
    shape.dispose();
    return body;
}
 
Example 11
Source File: WorldUtils.java    From martianrun with Apache License 2.0 5 votes vote down vote up
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();
    return body;
}
 
Example 12
Source File: PhysicsFactory.java    From tilt-game-android with MIT License 5 votes vote down vote up
/**
 * @param pPhysicsWorld
 * @param pEntity
 * @param pTriangleVertices are to be defined relative to the center of the pEntity and have the {@link PhysicsConstants#PIXEL_TO_METER_RATIO_DEFAULT} applied.
 * 					The vertices will be triangulated and for each triangle a {@link Fixture} will be created.
 * @param pBodyType
 * @param pFixtureDef
 * @return
 */
public static Body createTrianglulatedBody(final PhysicsWorld pPhysicsWorld, final IEntity pEntity, final List<Vector2> pTriangleVertices, final BodyType pBodyType, final FixtureDef pFixtureDef, final float pPixelToMeterRatio) {
	final Vector2[] TMP_TRIANGLE = new Vector2[3];

	final BodyDef boxBodyDef = new BodyDef();
	boxBodyDef.type = pBodyType;

	final float[] sceneCenterCoordinates = pEntity.getSceneCenterCoordinates();
	boxBodyDef.position.x = sceneCenterCoordinates[Constants.VERTEX_INDEX_X] / pPixelToMeterRatio;
	boxBodyDef.position.y = sceneCenterCoordinates[Constants.VERTEX_INDEX_Y] / pPixelToMeterRatio;

	final Body boxBody = pPhysicsWorld.createBody(boxBodyDef);

	final int vertexCount = pTriangleVertices.size();
	for (int i = 0; i < vertexCount; /* */) {
		final PolygonShape boxPoly = new PolygonShape();

		TMP_TRIANGLE[2] = pTriangleVertices.get(i++);
		TMP_TRIANGLE[1] = pTriangleVertices.get(i++);
		TMP_TRIANGLE[0] = pTriangleVertices.get(i++);

		boxPoly.set(TMP_TRIANGLE);
		pFixtureDef.shape = boxPoly;

		boxBody.createFixture(pFixtureDef);

		boxPoly.dispose();
	}

	return boxBody;
}
 
Example 13
Source File: ActorBuilder.java    From Bomberman_libGdx with MIT License 4 votes vote down vote up
public void createWall(float x, float y, float mapWidth, float mapHeight, TextureAtlas tileTextureAtlas) {
    BodyDef bodyDef = new BodyDef();
    bodyDef.type = BodyDef.BodyType.StaticBody;
    bodyDef.position.set(x, y);

    Body body = b2dWorld.createBody(bodyDef);
    PolygonShape polygonShape = new PolygonShape();
    polygonShape.setAsBox(0.5f, 0.5f);
    FixtureDef fixtureDef = new FixtureDef();
    fixtureDef.shape = polygonShape;
    fixtureDef.filter.categoryBits = GameManager.INDESTRUCTIIBLE_BIT;
    fixtureDef.filter.maskBits = GameManager.PLAYER_BIT | GameManager.ENEMY_BIT | GameManager.BOMB_BIT;
    body.createFixture(fixtureDef);

    polygonShape.dispose();

    Renderer renderer;

    if (x < 1.0f) {
        if (y < 1.0f) {
            renderer = new Renderer(new TextureRegion(tileTextureAtlas.findRegion("wall"), 0, 16 * 2, 16, 16), 16 / GameManager.PPM, 16 / GameManager.PPM);
        } else if (y > mapHeight - 1) {
            renderer = new Renderer(new TextureRegion(tileTextureAtlas.findRegion("wall"), 0, 16 * 0, 16, 16), 16 / GameManager.PPM, 16 / GameManager.PPM);

        } else {
            renderer = new Renderer(new TextureRegion(tileTextureAtlas.findRegion("wall"), 0, 16 * 1, 16, 16), 16 / GameManager.PPM, 16 / GameManager.PPM);

        }
    } else if (x > mapWidth - 1) {
        if (y < 1.0f) {
            renderer = new Renderer(new TextureRegion(tileTextureAtlas.findRegion("wall"), 16 * 2, 16 * 2, 16, 16), 16 / GameManager.PPM, 16 / GameManager.PPM);

        } else if (y > mapHeight - 1) {
            renderer = new Renderer(new TextureRegion(tileTextureAtlas.findRegion("wall"), 16 * 2, 16 * 0, 16, 16), 16 / GameManager.PPM, 16 / GameManager.PPM);

        } else {
            renderer = new Renderer(new TextureRegion(tileTextureAtlas.findRegion("wall"), 16 * 2, 16 * 1, 16, 16), 16 / GameManager.PPM, 16 / GameManager.PPM);

        }
    } else if (y < 1.0f) {
        renderer = new Renderer(new TextureRegion(tileTextureAtlas.findRegion("wall"), 16 * 1, 16 * 2, 16, 16), 16 / GameManager.PPM, 16 / GameManager.PPM);

    } else if (y > mapHeight - 1) {
        renderer = new Renderer(new TextureRegion(tileTextureAtlas.findRegion("wall"), 16 * 1, 16 * 0, 16, 16), 16 / GameManager.PPM, 16 / GameManager.PPM);

    } else {
        renderer = new Renderer(new TextureRegion(tileTextureAtlas.findRegion("wall"), 0, 0, 16, 16), 16 / GameManager.PPM, 16 / GameManager.PPM);
    }

    renderer.setOrigin(16 / GameManager.PPM / 2, 16 / GameManager.PPM / 2);
    new EntityBuilder(world)
            .with(
                    new Transform(x, y, 1f, 1f, 0),
                    renderer
            )
            .build();
}
 
Example 14
Source File: ActorBuilder.java    From Bomberman_libGdx with MIT License 4 votes vote down vote up
public void createPortal() {
    float x = GameManager.getInstance().getPortalPosition().x;
    float y = GameManager.getInstance().getPortalPosition().y;

    BodyDef bodyDef = new BodyDef();
    bodyDef.type = BodyDef.BodyType.KinematicBody;
    bodyDef.position.set(x + 0.5f, y + 0.5f);

    Body body = b2dWorld.createBody(bodyDef);

    PolygonShape polygonShape = new PolygonShape();
    polygonShape.setAsBox(0.2f, 0.2f);
    FixtureDef fixtureDef = new FixtureDef();
    fixtureDef.shape = polygonShape;
    fixtureDef.filter.categoryBits = GameManager.PORTAL_BIT;
    fixtureDef.filter.maskBits = GameManager.PLAYER_BIT;
    fixtureDef.isSensor = true;
    body.createFixture(fixtureDef);

    polygonShape.dispose();

    TextureRegion textureRegion = assetManager.get("img/actors.pack", TextureAtlas.class).findRegion("Items");
    Array<TextureRegion> keyFrames = new Array<>();
    for (int i = 6; i < 8; i++) {
        keyFrames.add(new TextureRegion(textureRegion, i * 16, 0, 16, 16));
    }
    Animation anim = new Animation(0.2f, keyFrames, Animation.PlayMode.LOOP);

    HashMap<String, Animation> anims = new HashMap<>();
    anims.put("normal", anim);

    Transform transform = new Transform(body.getPosition().x, body.getPosition().y, 1, 1, 0);
    transform.z = 99; // make portal drawn below player
    Renderer renderer = new Renderer(textureRegion, 16 / GameManager.PPM, 16 / GameManager.PPM);
    renderer.setOrigin(16 / GameManager.PPM / 2, 16 / GameManager.PPM / 2);

    Entity e = new EntityBuilder(world)
            .with(
                    transform,
                    new State("normal"),
                    new Anim(anims),
                    renderer
            )
            .build();

    body.setUserData(e);
}
 
Example 15
Source File: PhysicsFactory.java    From tilt-game-android with MIT License 4 votes vote down vote up
/**
 * @param pPhysicsWorld
 * @param pEntity
 * @param pVertices are to be defined relative to the center of the pEntity.
 * @param pBodyType
 * @param pFixtureDef
 * @return
 */
public static Body createPolygonBody(final PhysicsWorld pPhysicsWorld, final IEntity pEntity, final Vector2[] pVertices, final BodyType pBodyType, final FixtureDef pFixtureDef, final float pPixelToMeterRatio) {
	final BodyDef boxBodyDef = new BodyDef();
	boxBodyDef.type = pBodyType;

	final float[] sceneCenterCoordinates = pEntity.getSceneCenterCoordinates();
	boxBodyDef.position.x = sceneCenterCoordinates[Constants.VERTEX_INDEX_X] / pPixelToMeterRatio;
	boxBodyDef.position.y = sceneCenterCoordinates[Constants.VERTEX_INDEX_Y] / pPixelToMeterRatio;

	final Body boxBody = pPhysicsWorld.createBody(boxBodyDef);

	final PolygonShape boxPoly = new PolygonShape();

	boxPoly.set(pVertices);
	pFixtureDef.shape = boxPoly;

	boxBody.createFixture(pFixtureDef);

	boxPoly.dispose();

	return boxBody;
}
 
Example 16
Source File: PhysicsFactory.java    From tilt-game-android with MIT License 4 votes vote down vote up
public static Body createLineBody(final PhysicsWorld pPhysicsWorld, final float pX1, final float pY1, final float pX2, final float pY2, final FixtureDef pFixtureDef, final float pPixelToMeterRatio) {
	final BodyDef lineBodyDef = new BodyDef();
	lineBodyDef.type = BodyType.StaticBody;

	final Body boxBody = pPhysicsWorld.createBody(lineBodyDef);

	final PolygonShape linePoly = new PolygonShape();

	linePoly.setAsEdge(new Vector2(pX1 / pPixelToMeterRatio, pY1 / pPixelToMeterRatio), new Vector2(pX2 / pPixelToMeterRatio, pY2 / pPixelToMeterRatio));
	pFixtureDef.shape = linePoly;

	boxBody.createFixture(pFixtureDef);

	linePoly.dispose();

	return boxBody;
}
 
Example 17
Source File: PhysicsFactory.java    From tilt-game-android with MIT License 4 votes vote down vote up
public static Body createCircleBody(final PhysicsWorld pPhysicsWorld, final float pCenterX, final float pCenterY, final float pRadius, final float pRotation, final BodyType pBodyType, final FixtureDef pFixtureDef, final float pPixelToMeterRatio) {
	final BodyDef circleBodyDef = new BodyDef();
	circleBodyDef.type = pBodyType;

	circleBodyDef.position.x = pCenterX / pPixelToMeterRatio;
	circleBodyDef.position.y = pCenterY / pPixelToMeterRatio;

	circleBodyDef.angle = MathUtils.degToRad(pRotation);

	final Body circleBody = pPhysicsWorld.createBody(circleBodyDef);

	final CircleShape circlePoly = new CircleShape();
	pFixtureDef.shape = circlePoly;

	final float radius = pRadius / pPixelToMeterRatio;
	circlePoly.setRadius(radius);

	circleBody.createFixture(pFixtureDef);

	circlePoly.dispose();

	return circleBody;
}
 
Example 18
Source File: PhysicsFactory.java    From tilt-game-android with MIT License 4 votes vote down vote up
public static Body createBoxBody(final PhysicsWorld pPhysicsWorld, final float pCenterX, final float pCenterY, final float pWidth, final float pHeight, final float pRotation, final BodyType pBodyType, final FixtureDef pFixtureDef, final float pPixelToMeterRatio) {
	final BodyDef boxBodyDef = new BodyDef();
	boxBodyDef.type = pBodyType;

	boxBodyDef.position.x = pCenterX / pPixelToMeterRatio;
	boxBodyDef.position.y = pCenterY / pPixelToMeterRatio;

	final Body boxBody = pPhysicsWorld.createBody(boxBodyDef);

	final PolygonShape boxPoly = new PolygonShape();

	final float halfWidth = pWidth * 0.5f / pPixelToMeterRatio;
	final float halfHeight = pHeight * 0.5f / pPixelToMeterRatio;

	boxPoly.setAsBox(halfWidth, halfHeight);
	pFixtureDef.shape = boxPoly;

	boxBody.createFixture(pFixtureDef);

	boxPoly.dispose();

	boxBody.setTransform(boxBody.getWorldCenter(), MathUtils.degToRad(pRotation));

	return boxBody;
}
 
Example 19
Source File: BodyEditorLoader.java    From uracer-kotd with Apache License 2.0 4 votes vote down vote up
/** Creates and applies the fixtures defined in the editor. The name parameter is used to retrieve the right fixture from the
 * loaded file. <br/>
 * <br/>
 * 
 * The body reference point (the red cross in the tool) is by default located at the bottom left corner of the image. This
 * reference point will be put right over the BodyDef position point. Therefore, you should place this reference point
 * carefully to let you place your body in your world easily with its BodyDef.position point. Note that to draw an image at the
 * position of your body, you will need to know this reference point (see {@link #getOrigin(java.lang.String, float)}. <br/>
 * <br/>
 * 
 * Also, saved shapes are normalized. As shown in the tool, the width of the image is considered to be always 1 meter. Thus,
 * you need to provide a scale factor so the polygons get resized according to your needs (not every body is 1 meter large in
 * your game, I guess).
 * 
 * @param body The Box2d body you want to attach the fixture to.
 * @param name The name of the fixture you want to load.
 * @param fd The fixture parameters to apply to the created body fixture.
 * @param scale The desired scale of the body. The default width is 1. */
public void attachFixture (Body body, String name, FixtureDef fd, float scale, float scaleX, float scaleY) {
	RigidBodyModel rbModel = model.rigidBodies.get(name);
	if (rbModel == null) {
		throw new RuntimeException("Name '" + name + "' was not found.");
	}

	Vector2 origin = vec.set(rbModel.origin).scl(scale);

	for (int i = 0, n = rbModel.polygons.size(); i < n; i++) {
		PolygonModel polygon = rbModel.polygons.get(i);
		Vector2[] vertices = polygon.buffer;

		for (int ii = 0, nn = vertices.length; ii < nn; ii++) {
			vertices[ii] = newVec().set(polygon.vertices.get(ii)).scl(scale);
			vertices[ii].sub(origin);
			vertices[ii].x *= scaleX;
			vertices[ii].y *= scaleY;
		}

		polygonShape.set(vertices);
		fd.shape = polygonShape;
		body.createFixture(fd);

		for (int ii = 0, nn = vertices.length; ii < nn; ii++) {
			free(vertices[ii]);
		}
	}

	for (int i = 0, n = rbModel.circles.size(); i < n; i++) {
		CircleModel circle = rbModel.circles.get(i);
		Vector2 center = newVec().set(circle.center).scl(scale);
		float radius = circle.radius * scale;

		circleShape.setPosition(center);
		circleShape.setRadius(radius);
		fd.shape = circleShape;
		body.createFixture(fd);

		free(center);
	}
}
 
Example 20
Source File: Box2DFactory.java    From uracer-kotd with Apache License 2.0 4 votes vote down vote up
/** Creates a wall by constructing a rectangle whose corners are (xmin,ymin) and (xmax,ymax), and rotating the box
 * counterclockwise through the given angle, with specified restitution. */
public static Body createWall (World world, float xmin, float ymin, float xmax, float ymax, float angle, float restitution) {
	float cx = (xmin + xmax) / 2;
	float cy = (ymin + ymax) / 2;
	float hx = (xmax - xmin) / 2;
	float hy = (ymax - ymin) / 2;
	if (hx < 0) {
		hx = -hx;
	}

	if (hy < 0) {
		hy = -hy;
	}

	PolygonShape wallshape = new PolygonShape();
	wallshape.setAsBox(hx, hy, new Vector2(0f, 0f), angle);

	FixtureDef fdef = new FixtureDef();
	fdef.shape = wallshape;
	fdef.density = 1.0f;
	fdef.friction = 0.02f;

	fdef.filter.groupIndex = CollisionFilters.GroupTrackWalls;
	fdef.filter.categoryBits = CollisionFilters.CategoryTrackWalls;
	fdef.filter.maskBits = CollisionFilters.MaskWalls;

	if (Config.Debug.TraverseWalls) {
		fdef.filter.groupIndex = CollisionFilters.GroupNoCollisions;
	}

	if (restitution > 0) {
		fdef.restitution = restitution;
	}

	BodyDef bd = new BodyDef();
	bd.position.set(cx, cy);
	Body wall = world.createBody(bd);
	wall.createFixture(fdef);
	wall.setType(BodyDef.BodyType.StaticBody);
	return wall;
}