1

我正在 Libgdx 中制作一个游戏,我想在其中将一个球从上字落到下字并将背景移向上字并根据它更新相机。我的代码如下...

    public WorldRenderer(SpriteBatch spriteBatch, World world){
  this.world = world;
  this.camera = new OrthographicCamera(FRUSTUM_WIDTH, FRUSTUM_HEIGHT);
  this.camera.position.set(FRUSTUM_WIDTH/2, FRUSTUM_HEIGHT/2, 0);
  this.spriteBatch = spriteBatch;
  positionBGY1 = 0;
  positionBGY2 = 0;

 }
 public void render(World world, float deltaTime){
  if(world.ball.position.y > - camera.position.y){
    camera.position.y = world.ball.position.y;

  }

  if(camera.position.y<0)
   camera.position.y=world.ball.position.y;

  camera.update();
  spriteBatch.setProjectionMatrix(camera.combined);
  renderBackground();
  renderObjects(world, deltaTime);
 }


 private void calculateBGPosition(){
  positionBGY2 = positionBGY1 + (int)FRUSTUM_HEIGHT;
  if(camera.position.y >= positionBGY2){
   positionBGY1 = positionBGY2;
  }
 }
 private void renderBackground() {
  spriteBatch.disableBlending();
  spriteBatch.begin();
  spriteBatch.draw(Assets.gamebackgroundRegion, camera.position.x - FRUSTUM_WIDTH / 2, positionBGY1 - FRUSTUM_HEIGHT / 2, FRUSTUM_WIDTH, 1.5f * FRUSTUM_HEIGHT);
  spriteBatch.draw(Assets.gamebackgroundRegion2, camera.position.x - FRUSTUM_WIDTH / 2, positionBGY2 - FRUSTUM_HEIGHT / 2, FRUSTUM_WIDTH, 1.5f * FRUSTUM_HEIGHT);
  calculateBGPosition();
  spriteBatch.end();
  }

我的代码的问题是背景屏幕没有移动,相机没有随着球的移动而更新,球从屏幕上掉下来。

4

2 回答 2

1

好吧,您需要做的第一件事是更改其中一个 bg 变量,因此在渲染中执行以下操作:

float speed = 1;
positionBGY1+=deltaTime*speed;
positionBGY2+=deltaTime*speed;

至于相机随球移动,我会这样做:

camera.position.y = Math.min(ball.y,0);

我会反过来省略所有这些:

if(world.ball.position.y > - camera.position.y){
    camera.position.y = world.ball.position.y;
}

if(camera.position.y<0)
    camera.position.y=world.ball.position.y;
于 2013-06-16T02:40:48.957 回答
0

实现这一点的最佳方法是使用 ParrallaxLayer 和 ParrallaxBackground 类

它优化了后台操作,因此您不必担心性能

于 2013-06-20T07:45:49.543 回答