0

I have a smasher game project and having problem when the game switches from MainMenuScreen to MainGameScreen, because of camera.unproject.

Texture img;
Array<Rectangle> listBalloon;
long lastSpawnTime;
OrthographicCamera camera;

BalloonPopper game;

public MainGameScreen(BalloonPopper game) {
    this.game = game;
    listBalloon = new Array<Rectangle>();
    spawnBalloon();
}

@Override
public void show() {
    img = new Texture("testBalloon.png");
}

@Override
public void render(float delta) {
    ScreenUtils.clear(1, 0, 0, 1);

    game.batch.begin();
    for(Rectangle blns: listBalloon) {
        game.batch.draw(img, blns.x, blns.y, blns.width,blns.height);
    }
    game.batch.end();

    if(TimeUtils.nanoTime() - lastSpawnTime > 1000000000) spawnBalloon();

    for(Iterator<Rectangle> iter = listBalloon.iterator(); iter.hasNext();) {
        Rectangle blns = iter.next();
        blns.y += 200 * Gdx.graphics.getDeltaTime();
        if(blns.y > 720) iter.remove();
        if(Gdx.input.isTouched()) {
            Vector3 blnXY = new Vector3();
            blnXY.set(Gdx.input.getX(), Gdx.input.getY(), 0);
            camera.unproject(blnXY);
            if(blns.contains(blnXY.x, blnXY.y)) {
                iter.remove();
            }
        }
    }
}

public void spawnBalloon() {
    Rectangle bln = new Rectangle();
    bln.x = MathUtils.random(0, 480 - 64);
    bln.y = -20;
    bln.width = 64;
    bln.height = 128;
    listBalloon.add(bln);
    lastSpawnTime = TimeUtils.nanoTime();
}

In for(Iterator<Rectangle> iter = listBalloon.iterator(); iter.hasNext();) in render(), if I remove the camera.unproject, the program will move to MainGameScreen with no problem. However, sometimes clicking the spawned texture won't remove them and i have to click like a bit above of the texture so it can be removed. So the only thing i know to make it precisely find the location when clicking, is by adding camera.unproject. But yeah the problem is the null pointer exception.

So is there a way to fix this? THX !!

Rainer's
  • 31
  • 2
  • Does this answer your question? [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Progman Jun 13 '21 at 08:30
  • Welcome to StackOverflow. The `camera` is declared, but never used (therefore the NullPointerException). But since it is not used anywhere it won't have any effect anyway. If you are using a camera in your `ViewPort` you need to use the same camera object, that you used in the ViewPort (not any camera object, that you created in MainGameScreen). If you need help on this, you need up edit the question and add the parts of the code where the `ViewPort`, the `MainGameScreen` and the `MainMenuScreen` are created. – Tobias Jun 15 '21 at 12:54

0 Answers0