javalibgdxspritetiledtmx

libGDX Tiled Map hiding sprites that are out of viewport


I started to create a 2D game using libGDX and Tiled as map creator. I am using some sprites as Collection of Images in Tiled.

The problem is that whenever I move to the right and some sprite's bottom left point is out of viewport it dissapears like this:

Missing wall, ceiling and floor

There's supposed to be a wall, part of ceiling and part of floor on the left side, but it dissapeared when I moved to the right.

This is my code:

public class Main implements ApplicationListener {
    private static final int VIEWPORT_WIDTH = 800;
    private static final int VIEWPORT_HEIGHT = 480;

    private TiledMap tiledMap;
    private TiledMapRenderer tiledMapRenderer;
    private OrthographicCamera camera;

    private SpriteBatch batch;

    private Texture playerImage;
    private Rectangle playerRect;

    @Override
    public void create() {
        this.camera = new OrthographicCamera();
        this.camera.setToOrtho(false, VIEWPORT_WIDTH, VIEWPORT_HEIGHT);
        this.camera.update();

        this.tiledMap = new TmxMapLoader().load("levels/demo_4x.tmx");
        this.tiledMapRenderer = new OrthogonalTiledMapRenderer(this.tiledMap);

        this.batch = new SpriteBatch();
        this.font = new BitmapFont();

        this.playerImage = new Texture(Gdx.files.internal("person-demo.gif"));
        this.playerRect = new Rectangle();
        this.playerRect.x = 276;
        this.playerRect.y = 88;
        this.playerRect.width = 128;
        this.playerRect.height = 128;
    }

    @Override
    public void render() {
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glBlendFunc(GL30.GL_SRC_ALPHA, GL30.GL_ONE_MINUS_SRC_ALPHA);
        Gdx.gl.glClear(GL30.GL_COLOR_BUFFER_BIT);

        this.camera.position.x = this.playerRect.x + (this.playerRect.width / 2);
        this.camera.position.y = this.playerRect.y + (this.playerRect.height / 2);
        this.camera.update();
        this.tiledMapRenderer.setView(this.camera);
        this.tiledMapRenderer.render();

        this.batch.begin();

        this.batch.draw(this.playerImage, this.playerRect.x, this.playerRect.y, this.playerRect.width, this.playerRect.height);

        this.batch.end();
        this.batch.setProjectionMatrix(this.camera.combined);
    }
}

I can't figure out how to solve this issue whole day. I hope someone will be able to.


Solution

  • You can just add a off set when setting the tiledMapRenderer.setView(cam);

    Instead of that do

    float width = cam.viewportWidth *cam.zoom;
    float height = cam.viewportHeight * cam.zoom;
    
    float w = width * Math.abs(cam.up.y) + height * Math.abs(cam.up.x);
    float h = height * Math.abs(cam.up.y) + width * Math.abs(cam.up.x);
    float x = cam.position.x - w / 2;
    float y = cam.position.y - h / 2;
    
    x -= offset;
    w += offset;
    tiledMapRenderer.setView(cam.combined,x,y,w,h);