【发布时间】:2014-07-13 21:03:39
【问题描述】:
我正在尝试学习 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);
}
【问题讨论】:
-
一目了然,我没有发现任何问题。我建议您测试所有 3 个机构是否都满足执行“setTeansform”的条件。您可以通过将 if 中的变量 body2 中您最感兴趣的值写入日志来做到这一点。