Search code examples
javatimerlibgdx

Java Timer crashes my libGdx game


I'm making match3 game on libGdx. After scanning for matches I have to wait for animations to complete and run scanning again until no more matches left. I do it with Java Timer and when I run application on desktop it works fine but on Android device it crashes after one, two or few more iterations. Any ideas what is wrong?

    Timer animationTimer;

    scanForMatches(){
        //do some stuff
        //...

        checkAnimationComplete();
    }

    checkAnimationComplete(){
        animationTimer = new Timer();

        animationTimer.scheduleAtFixedRate(new TimerTask(){
            @Override
            public void run() {
                boolean animDone = true;

                // do some stuff to
                // check if anim done

                if (animDone){
                    animationTimer.cancel();
                    scanForMatches();
                } 
            }
        }, 1000, 100);
    }

Solution

  • Without looking at the rest of your code, I would highly suggest dropping the timer altogether as it is almost certainly unnecessary in this case and not very efficient. Are you using an Action to animate with a stage, or are you manually moving things based on position in draw()? If you are just moving something in draw(), I would use a boolean flag to signal that it has reached it's destination, like if you are dropping down solved tiles or something. If you are using an Action, it is possible to use a new Action to act as a callback like the following...

         myGem.addAction(Actions.sequence(
                        Actions.moveTo(230f, 115f, 0.25f, Interpolation.linear),
                        new Action() {
                            public boolean act(float delta) {
                                System.out.println("Done moving myGem!");
                                 scanForMatches();
                                return true;
                            }
                        }));
    

    There are quite a few ways to do what you're looking for depending on how you have your grid set up. Post up how you are animating whatever it is so I can take a look. Basically, you need to know exactly when it is done animating so that you can fire off your scan method again.