Scrolling Background Explanation - UQdeco2800/2021-ext-studio-2 GitHub Wiki
Overview
In sprint 2 we decided to design the game background and finish the implementation according to the Gamestory. Current background image is here.
Code implementation
BackgroundRenderComponent
Under the com/deco2800/game/rendering package. We created a new BackgroundRenderComponent.java class. The aim of creating this class is to create an object which can render the background image texture.
- The texture path is required in the constructor. This will be efficient for adding different background images(p.s. could be helpful in multiple maps)
    public BackgroundRenderComponent(String texturePath) {
        this.texturePath = texturePath;
    }
2.Considering that the background image needs to be rendered repeatedly during the game. We came out with the solution by creating a global variable private float horizontaland set it default to zero. Then create a public function to allow changing the horizontal variable manually.
    /**
     * Set the horizontal start point for the background texture
     * @param x horizontal value
     */
    public void setHorizontal(float x) {
        horizontal = x;
    }
Then, override the following function so that the background image can be drew from different horizontal start point.
    @Override
    public void draw(SpriteBatch batch) {
        batch.draw(texture, -30, 0, 30, 15);
        batch.draw(texture, horizontal, 0, 30, 15);
    }
3.Under com/deco2800/game/areas/ForestGameArea.java, two core functions have been added.
The showBackground() can be called to render the background from the beginning.
    private void showBackground() {
        Entity gameBg = new Entity();
        gameBg.addComponent(new BackgroundRenderComponent("images/background.png"));
        spawnEntity(gameBg);
    }
And the showScrollingBackground(int counter) need to be passed into a count number, which will render the background again and again.
    public void showScrollingBackground(int counter) {
        Entity gameBg = new Entity();
        BackgroundRenderComponent newBg = new BackgroundRenderComponent("images/background.png");
        newBg.setHorizontal(30f * counter);
        gameBg.addComponent(newBg);
        spawnEntity(gameBg);
    }
4.Under the render() function in com/deco2800/game/screens/MainGameScreen.java, the background will be rendered repeatedly until the loop terminate.
    ...
    // infinite loop for terrain and obstacles
    if(screenVector.x > (2*counter+1)*10) {
      counter+=1;
      forestGameArea.showScrollingBackground(counter);
    ...