I am trying to make an android game by the help of libGDX. My game is in portrait mode. Bird texture is rendering via for loop with a random OffSet. Sometimes my birds render outside of the screen. Here is my code for rendering:
if (birdX>Gdx.graphics.getWidth()) {
birdY = Gdx.graphics.getHeight()/2;
birdX = Gdx.graphics.getWidth()-birdX-numberOfBirds*distanceBird;
bird2X = bird2X + numberOfBirds*distanceBird+Gdx.graphics.getWidth();
birdOffSet1[i] = (random.nextFloat()-0.5f)*(Gdx.graphics.getHeight()/2-200);
birdOffSet2[i] = (random.nextFloat()-0.5f)*(Gdx.graphics.getHeight()/2-200);
} else {
birdX = birdX + cloudVelocity + 2;
bird2X = bird2X - cloudVelocity -2;
}
batch.draw(bird1,birdX,birdY+birdOffSet1[i],Gdx.graphics.getWidth()/8,Gdx.graphics.getHeight()/18);
batch.draw(bird2,bird2X,birdY+birdOffSet2[i],Gdx.graphics.getWidth()/8,Gdx.graphics.getHeight()/18);
}
And values of the variables are:
numberOfBirds is 1,
distanceBird is 0
float[] birdOffSet1 = new float[numberOfBirds];
float[] birdOffSet2 = new float[numberOfBirds];
float birdX=-100;
float birdY=0;
float bird2X=1100;
I don't want to render my birds outside of the screen randomly. I hope you can help me, thank you.
graphics.getWidth()
(and height), you should be using the camera'sviewportWidth
andviewportHeight
. These are the actual bounds of the view in your game's coordinates. And you need to take into account the camera's position. For example, if the camera is at x=0 and y=0, the left edge of the view is-camera.viewportWidth / 2f
. But if the camera is ax=viewportWidth/2f
, then the left edge of the view is at x=0.