Search code examples
androidlibgdx

Libgdx Image and ShapeRenderer different behaviour on x axis


I am currently working on a Worms-like game. I generate random Levels, which holds an Array of Points for each x with corresponding y. Also i have two arrays with some x values, where I then place trees and huts. I use a Orthographic camera and the translate method to move the camera when the user touches the screen. In order to have big levels, I decided to render the map only for the part that is currently visible. for that I have a BackgroundActor, which gets the current position of the camera, from that information I get the corresponding part of my map from the level class with the surface array. I then render this information with a ShapeRenderer. Then I render the props (trees and huts). The problem is, that the props get unaligned with the surface, when I drag the screen. For example: I move the map to the left, and the surface is moving faster to the left than the props. I already tried to set the projection Matrix for both the SpriteBatch and the ShapeRenderer, but it did not help. Code:

@Override
public void draw(Batch batch, float parentAlpha) {
    setBounds(); //gets the index for my map array from the camera
    ShapeRenderer shapeRenderer = AndroidLauncher.gameScreen.shapeRenderer;
    batch.end(); //needed, because otherwise the props do not render
    shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);
    for (int x = 0; x < ScreenValues.screenWidth; x++) {
        int y = level.getYForX(x + leftBound);
        shapeRenderer.setColor(level.getUndergroundColor());
        shapeRenderer.rectLine(x, 0, x, y - level.getSurfaceThickness(), 1);
        shapeRenderer.setColor(level.getSurfaceColor());
        shapeRenderer.rectLine(x, y - level.getSurfaceThickness(), x, y, 1);
    }

    shapeRenderer.end();
    batch.begin();

    for (int x = 0; x < ScreenValues.screenWidth; x++) {
        int y = level.getYForX(x + leftBound);
        if (level.getPropForX(x) != Level.PROP_NONE) {
            if (level.getPropForX(x) == Level.PROP_TREE) y -= 10;
            Image imageToDraw = getImageFromPropId(level.getPropForX(x)); //Images are setup in the create method of my Listener
            imageToDraw.setPosition(x, y);
            imageToDraw.draw(batch, parentAlpha);
        }
    }
}

Solution

  • I fixed the issue myself. In the for loop for the props I needed to run x from leftBound to ScreenValues.screenWidth + leftBound. This still gives me Texture popping when the props get to the left side of the screen, because the props x position is out of screen, but this will be a small fix.