我正在尝试学习box2d,但我遇到了问题。我的项目中有3个实体,实际上有3个实体。我正在尝试将每个y坐标设置为-7到达y坐标14.我检查它们是否超过14的代码如下:
for (int i = 0; i < groundsArray.size(); i++) {
Body body2 = groundsArray.get(i);
float x_deg;
x_deg = body2.getTransform().getPosition().x;
if (body2.getUserData().equals("grounds" + i) && body2.getTransform().getPosition().y > 14) {
body2.setTransform(x_deg, -7, 0);
}
}
我如何创造身体:
public void createGrounds(int i) {
// for some random positions
int rnd = random.nextInt(10);
int constant = -20;
int new_y = i * 7;
int result_x1 = constant + rnd;
int result_x2 = result_x1 + 16;
BodyDef bodyDef = new BodyDef();
FixtureDef fixtureDef = new FixtureDef();
// GROUND LEFT
// body definition
bodyDef.type = BodyType.StaticBody;
bodyDef.position.set(0, 0);
// ground shape
ChainShape groundShape = new ChainShape();
groundShape.createChain(new Vector2[] { new Vector2(result_x1, -new_y),new Vector2(result_x2, -new_y) });
// fixture definition
fixtureDef.shape = groundShape;
fixtureDef.friction = 5f;
fixtureDef.restitution = 0;
grounds = world.createBody(bodyDef);
grounds.createFixture(fixtureDef);
grounds.setUserData("grounds" + i);
groundsArray.add(grounds);
groundShape.dispose();
}
我如何调用show()中的createGrounds():
for (int i = 0; i <= 2; i++) {
createGrounds(i);
}
我如何更新render()中的世界和位置:
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0, 0);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
accelX = Gdx.input.getAccelerometerX();
Vector2 gravity = new Vector2(-accelX * 6, -60.81f);
world.setGravity(gravity);
world.step(TIMESTEP, VELOCITYITERATIONS, POSITIONITERATIONS);
batch.setProjectionMatrix(camera.combined);
batch.begin();
world.getBodies(tmpBodies);
for (Body body : tmpBodies) {
if (body.getUserData().equals(ballsprite)
&& body.getUserData() instanceof Sprite) {
Sprite sprite = (Sprite) body.getUserData();
sprite.setPosition(
body.getPosition().x - sprite.getWidth() / 2,
body.getPosition().y - sprite.getHeight() / 2);
sprite.setRotation(body.getAngle() * MathUtils.radiansToDegrees);
sprite.draw(batch);
}
float x_deg;
float y_deg;
x_deg = body.getTransform().getPosition().x;
y_deg = body.getTransform().getPosition().y;
y_deg = y_deg + game_speed;
body.setTransform(x_deg, y_deg, 0);
}
// The part i couldn't solve
for (int i = 0; i < groundsArray.size(); i++) {
Body body2 = groundsArray.get(i);
float x_deg;
x_deg = body2.getTransform().getPosition().x;
if (body2.getUserData().equals("grounds" + i)
&& body2.getTransform().getPosition().y > 14) {
body2.setTransform(x_deg, -7, 0);
}
}
batch.end();
debugRenderer.render(world, camera.combined);
}
答案 0 :(得分:0)
也许将你的周期改为
for(int i = groundsArray.size(); i > 0; i--){}