OneSurvivor
OneSurvivor

Reputation: 494

Thread.sleep appears to be very inconsistent

This method below is attempting to move a sprite int a "block" maze, and I need it to wait every so often each "step" then move again and repaint, but this method just leads to the guy taking forever to move, and then teleporting to the needed destination.

Is there something I am doing wrong with the sleep method?

public void rightClick() {
    while(select.x != mouseConverter(mouseX) && select.y != mouseConverter(mouseY)) {
        int[][] path = select.ai().getPath(arena, mouseConverter(mouseX), mouseConverter(mouseY), blocked);
        select.move(path[0][0], path[0][1]);
        repaint();
        try {
            Thread.sleep(1000);
        } catch(InterruptedException ex) {
            System.out.println("Inturrupted");
            Thread.currentThread().interrupt();

        }
    }
}

This probably needs a lot of clarification, so forgive me if this is extremely confusing.

Upvotes: 0

Views: 189

Answers (1)

OneSurvivor
OneSurvivor

Reputation: 494

Okay, thank you @VGR for tipping me off about the issues with AWT/Swing, although in the end I believe that is was a comparator error on my part. Here is the updated code:

public void rightClick() {
    TimerTask task;

    task = new TimerTask() {
        @Override
        public void run() {
            System.out.println("X: " + mouseConverter(mouseX) + " Y: " + mouseConverter(mouseY));
            System.out.println("SX: " + select.x + " SY: " + select.y);
            if (select.x != mouseConverter(mouseX) || select.y != mouseConverter(mouseY)) {
                int[][] path = select.ai().getPath(arena, mouseConverter(mouseX), mouseConverter(mouseY), blocked);
                select.move(path[0][0], path[0][1]);
                repaint();
            }
            else {
                cancel();

            }
        }
    };
    timer.schedule(task, 0, ANIMATION_DELAY);

}

After I updated the code to work with a timer, I ran into the issue where I could not move if the X value or Y value was the same as the X or Y value of the sprite. After an hour of work, the main issue was not only the Timer, but also my comparator error, working together to make the perfect issue.

Upvotes: 1

Related Questions