Skip to content Skip to sidebar Skip to footer

Libgdx Change Background After Three Attempts

I'll formulate my previous question again. I want the background of my game change from day to night. This should be done after two or three tries to play the game. I have óne tex

Solution 1:

Well, Lets say you have a Sprite that holds the whole texture.

SpritetimeOfDay=newSprite(texture);

Then by simply tweaking your changeBG(int x) method. You can appropriately set the sprite to the Region you want.

public void changeBG(int x){
    if(x < 5) //Assuming x is the time
        timeOfDay.setRegion(DAY);
    else
        timeOfDay.setRegion(NIGHT);
}

and then in your draw() method after you set the batch up

timeOfDay.draw(batch);

I hope this helps.

[Update]

No need to draw DAY and NIGHT in your render method. Time of Day holds the DAY and NIGHT textures. When you call

timeOfDay.draw(batch); 

it renders the setRegion.

Your render should look something like this....

public void draw(){
    batcher.begin();
    timeOfDay.draw(batcher);
    batcher.end();
}

Solution 2:

As I've partially said in the previous answer, what you need to do from scratch is pretty much the following:

DAY=new TextureRegion(texture, 0, 0, 287, 512);
DAY.flip(false, true);
NIGHT=new TextureRegion(texture, 291, 0, 287,512);
NIGHT.flip(false, true);

Then you create a Sprite:

Spritesprite=newSprite(DAY);

I'm guessing you will set it to the size of the screen, which depends on whether you use Scene2d or an Orthogonal transform or just go at it plainly with screen coordinates:

sprite.setSize(Gdx.graphics.width, Gdx.graphics.height);

or

sprite.setSize(virtualWidth, virtualHeight); //in new version of LibGDX this is standard 640x480

And afterwards, based on the logic of the game, you will want to change the TextureRegion. To store how many times you've retried, you need to use the Preferences:

privatestaticPreferences preferences; 

@Overridepublicvoidcreate()
{
    preferences = Gdx.app.getPreferences(Resources.preferencesName);
    ...

publicstaticPreferencesgetPreferences()
{
    return preferences;
}

After which when the game ended, you do the following:

Where you add the number as the following at a game over to change the number of tries:

int currentTries = MyGame.getPreferences().getInt("numberOfTries");
    currentTries++;
    currentTries %= 6;
    MyGame.getPreferences().putInt("numberOfTries", currentTries);
    MyGame.getPreferences().flush();
    changeBG(currentTries);

And then you change the current texture region:

 public void changeBG(int x){
    if(x < 3) {
        sprite.setRegion(DAY);
    }
    else if (x < 6) {
        sprite.setRegion(NIGHT);
    }
 }

Post a Comment for "Libgdx Change Background After Three Attempts"