int amoumt = 10;
int i = 1;
while (i < amoumt+1)
{
box(1);//body
i++;
}
如果我使用这种方法,我会得到9个身体和一个没有精灵的身体。 但我在他们所有人身上花了一个精灵
在渲染方法中,用于在每个正文上绘制精灵:
batch.begin();
world.getBodies(worldBodies);
for (Body body : worldBodies) {
if (body.getUserData() instanceof Sprite) {
Sprite sprite = (Sprite) body.getUserData();
Vector2 position = body.getPosition();
sprite.setPosition(position.x - sprite.getWidth() / 2,position.y - sprite.getHeight() / 2);
sprite.setRotation(body.getAngle() * MathUtils.radiansToDegrees);
sprite.draw(batch);
}
}
batch.end();
}
体:
private Body box(float a)
{
BodyDef bodyDef = new BodyDef();
bodyDef.position.set(0,0);
bodyDef.type = BodyType.DynamicBody;
PolygonShape polygonShape=new PolygonShape();
polygonShape.setAsBox(a,a);
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape=polygonShape;
fixtureDef.density=2;
fixtureDef.restitution=0.5f;
fixtureDef.friction=0.5f;
Body box=world.createBody(bodyDef);
box.createFixture(fixtureDef);
box.setUserData(sprite);
sprite = new Sprite(new Texture("android.jpg"));
sprite.setSize(a*2,a*2);
sprite.setOrigin(sprite.getWidth() / 2, sprite.getHeight() / 2);
worldBodies = new Array<Body>();
return box;
}
答案 0 :(得分:1)
据我所知,当您创建第一个框时,您设置为用户数据的精灵不会被初始化。在将用户数据设置为精灵之前,请尝试移动sprite = new sprite
初始化行。
答案 1 :(得分:1)
我认为这将解决您的问题
private Body box(float a)
{
BodyDef bodyDef = new BodyDef();
bodyDef.position.set(0,0);
bodyDef.type = BodyType.DynamicBody;
PolygonShape polygonShape=new PolygonShape();
polygonShape.setAsBox(a,a);
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape=polygonShape;
fixtureDef.density=2;
fixtureDef.restitution=0.5f;
fixtureDef.friction=0.5f;
Body box=world.createBody(bodyDef);
box.createFixture(fixtureDef);
sprite = new Sprite(new Texture("android.jpg"));
sprite.setSize(a*2,a*2);
sprite.setOrigin(sprite.getWidth() / 2, sprite.getHeight() / 2);
box.setUserData(sprite);
worldBodies = new Array<Body>();
return box;
}
希望这很有用!