package uk.co.flyingsquirrels.models;
import org.jbox2d.collision.PolygonDef;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.BodyDef;
import org.jbox2d.dynamics.World;
public class Ground {
public Ground(World world, int worldWidth, int groundResolution,
float maxGroundElevation, float minGroundElevation) {
float heightMap[] = new float[worldWidth * 2 / groundResolution];
populateHeightMap(maxGroundElevation, heightMap);
for (int i = 0; i < heightMap.length - 1; i++) {
BodyDef bodyDef = new BodyDef();
Body ground = world.createBody(bodyDef);
float x1 = -worldWidth + i * groundResolution;
float x2 = x1 + groundResolution;
float y1 = heightMap[i];
float y2 = heightMap[i + 1];
PolygonDef polygonDef = createPolygon(x1, x2, y1, y2, minGroundElevation);
ground.createShape(polygonDef);
}
}
private void populateHeightMap(float maxGroundElevation, float[] heightMap) {
for (int i = 0; i < heightMap.length; i++) {
heightMap[i] = maxGroundElevation - (float) Math.random()
* maxGroundElevation;
}
}
private PolygonDef createPolygon(float x1, float x2, float y1, float y2, float minY) {
PolygonDef polygonDef = new PolygonDef();
polygonDef.addVertex(new Vec2(x2, y2));
polygonDef.addVertex(new Vec2(x1, y1));
polygonDef.addVertex(new Vec2(x1, minY));
polygonDef.addVertex(new Vec2(x2, minY));
return polygonDef;
}
}