有一種方法可以使用對象層。不要放棄希望!
此方法在使用瓦片屬性方面的一個主要優勢是您可以輕鬆生成更少,更大的物體以提高Box2d的效率。另外,更好的是,這些身體可以是任何你想要的形狀!在我的遊戲中,我的樣本水平現在只有三個有趣的形狀(看起來更有機體)ChainShape
爲基礎的身體,而不是幾十個平方身體。
I answered the same question前些日子在GameDev上,經過嚴重的網絡叢林深處追捕之後。該tutorial我發現沒有相當的工作對我來說,就是那麼一點點的編輯後,我想出了這個:
public class MapBodyBuilder {
// The pixels per tile. If your tiles are 16x16, this is set to 16f
private static float ppt = 0;
public static Array<Body> buildShapes(Map map, float pixels, World world) {
ppt = pixels;
MapObjects objects = map.getLayers().get("Obstacles").getObjects();
Array<Body> bodies = new Array<Body>();
for(MapObject object : objects) {
if (object instanceof TextureMapObject) {
continue;
}
Shape shape;
if (object instanceof RectangleMapObject) {
shape = getRectangle((RectangleMapObject)object);
}
else if (object instanceof PolygonMapObject) {
shape = getPolygon((PolygonMapObject)object);
}
else if (object instanceof PolylineMapObject) {
shape = getPolyline((PolylineMapObject)object);
}
else if (object instanceof CircleMapObject) {
shape = getCircle((CircleMapObject)object);
}
else {
continue;
}
BodyDef bd = new BodyDef();
bd.type = BodyType.StaticBody;
Body body = world.createBody(bd);
body.createFixture(shape, 1);
bodies.add(body);
shape.dispose();
}
return bodies;
}
private static PolygonShape getRectangle(RectangleMapObject rectangleObject) {
Rectangle rectangle = rectangleObject.getRectangle();
PolygonShape polygon = new PolygonShape();
Vector2 size = new Vector2((rectangle.x + rectangle.width * 0.5f)/ppt,
(rectangle.y + rectangle.height * 0.5f)/ppt);
polygon.setAsBox(rectangle.width * 0.5f/ppt,
rectangle.height * 0.5f/ppt,
size,
0.0f);
return polygon;
}
private static CircleShape getCircle(CircleMapObject circleObject) {
Circle circle = circleObject.getCircle();
CircleShape circleShape = new CircleShape();
circleShape.setRadius(circle.radius/ppt);
circleShape.setPosition(new Vector2(circle.x/ppt, circle.y/ppt));
return circleShape;
}
private static PolygonShape getPolygon(PolygonMapObject polygonObject) {
PolygonShape polygon = new PolygonShape();
float[] vertices = polygonObject.getPolygon().getTransformedVertices();
float[] worldVertices = new float[vertices.length];
for (int i = 0; i < vertices.length; ++i) {
worldVertices[i] = vertices[i]/ppt;
}
polygon.set(worldVertices);
return polygon;
}
private static ChainShape getPolyline(PolylineMapObject polylineObject) {
float[] vertices = polylineObject.getPolyline().getTransformedVertices();
Vector2[] worldVertices = new Vector2[vertices.length/2];
for (int i = 0; i < vertices.length/2; ++i) {
worldVertices[i] = new Vector2();
worldVertices[i].x = vertices[i * 2]/ppt;
worldVertices[i].y = vertices[i * 2 + 1]/ppt;
}
ChainShape chain = new ChainShape();
chain.createChain(worldVertices);
return chain;
}
}
假設您已經設置的東西,讓你的瓷磚的大小對應於1如果你喜歡Box2d World
,這個產生的靜態Body
就是你在平鋪的的地方。看到這件事情讓我感到非常滿意,相信你。
謝謝,這是驚人的,它與2d完美無瑕地工作! – im8bit