您有一个非常有用的链接,关于box2D和libgdx教授逻辑和渲染的概念。这里
然后您可以按照以下方式将逻辑部分与渲染部分分开:
逻辑部分:
private void createBottleBody() {
BodyEditorLoader loader = new BodyEditorLoader(sourceFile);
BodyDef bd = new BodyDef();
bd.position.set(0, 0);
bd.type = BodyType.DynamicBody;
FixtureDef fd = new FixtureDef();
fd.density = 1;
fd.friction = 0.5f;
fd.restitution = 0.3f;
bottleModel = world.createBody(bd);
loader.attachFixture(bottleModel, "test01", fd, BOTTLE_WIDTH);
}
渲染部分:
public void render() {
Vector2 bottlePos = bottleModel.getPosition().sub(bottleModelOrigin);
bottleSprite.setPosition(bottlePos.x, bottlePos.y);
bottleSprite.setOrigin(bottleModelOrigin.x, bottleModelOrigin.y);
bottleSprite.setRotation(bottleModel.getAngle() * MathUtils.radiansToDegrees);
...
}
加载器:在链接中可以找到一个加载器。
public void attachFixture(Body body, String name, FixtureDef fd, float scale) {
RigidBodyModel rbModel = (RigidBodyModel) this.model.rigidBodies.get(name);
if (rbModel == null)
throw new RuntimeException("Name '" + name + "' was not found.");
Vector2 origin = this.vec.set(rbModel.origin).mul(scale);
Vector2[] vertexes;
PolygonModel polygon;
for (int i = rbModel.polygons.size()-1; 0 <= i; i--) {
polygon = (PolygonModel) rbModel.polygons.get(i);
vertexes = polygon.vectorBuffer;
for (int ii = vertexes.length-1; 0 <= ii; ii--) {
vertexes[ii] = new Vector2().set((Vector2) polygon.vertices.get(ii)).mul(scale);
vertexes[ii].sub(origin);
}
this.polygonShape.set(vertexes);
fd.shape = this.polygonShape;
body.createFixture(fd);
}
CircleModel circle;
Vector2 center;
float radius;
for (int i = rbModel.circles.size()-1; 0 <= i; i--) {
circle = (CircleModel) rbModel.circles.get(i);
center = new Vector2().set(circle.center).mul(scale);
radius = circle.radius * scale;
this.circleShape.setPosition(center);
this.circleShape.setRadius(radius);
fd.shape = this.circleShape;
body.createFixture(fd);
}
}
最后...模型
public static class CircleModel {
public final Vector2 center = new Vector2();
public float radius;
}
public static class PolygonModel {
public final List<Vector2> vertices = new ArrayList<Vector2>();
private Vector2[] vectorBuffer;
}
public static class RigidBodyModel {
public String name;
public String imagePath;
public final Vector2 origin = new Vector2();
public final List<PolygonModel> polygons = new ArrayList<PolygonModel>();
public final List<CircleModel> circles = new ArrayList<CircleModel>();
}
public static class Model {
public final Map<String, RigidBodyModel> rigidBodies = new HashMap<String, RigidBodyModel>();
}
希望这能有所帮助!