因此,我在2d方块中进行游戏。一方面,我需要一个具有恒定反弹高度的球。我将球的恢复力设置为1,并且不对其施加任何力(当然,重力除外)。现在,这个球在每次弹跳时,每次弹跳都会更高一点,直到它离开屏幕的顶部边缘为止。此代码有什么问题?

    public class Ball implements ApplicationListener {
 World world ;
 Box2DDebugRenderer debugRenderer;
 OrthographicCamera camera;
 static final float BOX_STEP=1/60f;
 static final int BOX_VELOCITY_ITERATIONS=8;
 static final int BOX_POSITION_ITERATIONS=3;
 static final float WORLD_TO_BOX=0.01f;
 static final float BOX_WORLD_TO=100f;
 Rectangle ball;
 Body body;
 /* (non-Javadoc)
 * @see com.badlogic.gdx.ApplicationListener#create()
 */
@Override
 public void create() {
     world = new World(new Vector2(0, -10), true);
      camera = new OrthographicCamera();

      camera.viewportHeight = 480;
      camera.viewportWidth = 800;
      camera.position.set(camera.viewportWidth * .5f, camera.viewportHeight * .5f, 0f);
      camera.update();
      //Ground body
      BodyDef groundBodyDef =new BodyDef();
      groundBodyDef.position.set(new Vector2(0, 10 * WORLD_TO_BOX));
      Body groundBody = world.createBody(groundBodyDef);
      PolygonShape groundBox = new PolygonShape();
      float w = (camera.viewportWidth * 2) * WORLD_TO_BOX;
      float h = 10.0f * WORLD_TO_BOX;
      groundBox.setAsBox(w,h);
      groundBody.createFixture(groundBox, 0.0f);
      String a="gb";
      groundBody.setUserData(a);
      //Dynamic Body
      BodyDef bodyDef = new BodyDef();
      bodyDef.type = BodyType.DynamicBody;
      float posX = (camera.viewportWidth / 8) * WORLD_TO_BOX;
      float posY = (camera.viewportHeight / 2) * WORLD_TO_BOX;
      bodyDef.position.set(posX, posY);
      body = world.createBody(bodyDef);
   // create a Rectangle to logically represent the ball
      CircleShape dynamicCircle = new CircleShape();
      dynamicCircle.setRadius(1f);
      FixtureDef fixtureDef = new FixtureDef();
      fixtureDef.shape = dynamicCircle;
      fixtureDef.density = 1.0f;
      fixtureDef.friction = 0.0f;
      fixtureDef.restitution =1f;
      body.createFixture(fixtureDef);
      debugRenderer = new Box2DDebugRenderer();
 }
 @Override
 public void dispose() {
 }
 @Override
 public void render() {
      Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
      debugProjection.set(camera.combined);
      debugProjection.scl(BOX_WORLD_TO);
      debugRenderer.render(world, debugProjection);
      world.step(BOX_STEP, BOX_VELOCITY_ITERATIONS, BOX_POSITION_ITERATIONS);
          }



 @Override
 public void resize(int width, int height) {
 }
 @Override
 public void pause() {
 }
 @Override
 public void resume() {
 }
}

最佳答案

这可能是由numerical instability引起的。反复计算球的位置不可避免地会引入微小的数字误差(因为浮子只能容纳有限的数字)。这些可能会不断增长,并在迭代之间累加,反弹。

您可以尝试使用归还0.9999999之类的方法。但是很可能没有恢复价值可以提供预期的结果。

尝试积极补偿数值不稳定性,例如在您可以非迭代地计算值的情况下,通过控制球的位置和/或速度。 (我不知道Box2D。也许当球撞到地面时,您可以重置其速度或其他东西。)

08-05 07:39