1

Im making a game over the summer break and im having trouble with dealing with the walking animation. Im trying to put a stepping animation in between moving to the left or right trying to invoke repaint() for the first animation with a thread.sleep() inbetween followed by another repaint().

    case 65 :
        paintNum = 4;
        x = x-10;
        panel.changeNum(4);
        panel.setX(x);
        panel.repaint(200);
    
        
        try {
            
            Thread.sleep(200);
            
        } catch (InterruptedException e1) {
            
            e1.printStackTrace();
        }
        panel.changeNum(3);
        panel.repaint();
        
        
        //a
        break;

public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D)g;
    super.paintComponent(g);
    g2.drawImage(list.get(paintNum),x,y,50,50,null);
    

    
}
public void changeNum(int num) {
    paintNum =num;

    
}
public void setX(int num) {
    x = x +num;

}
public void setY(int num) {
    y = y+  num;
    
}

My code takes the break but skips the first repaint and goes straight to the second one. For context I have the movement in a switch case in another class that calls on the paint() method in my panel class. The paintNum is just the number for an array of the walking images.

  • 1
    Remember that Swing is a desktop GUI, not a game engine. "Efficiency" means sometimes combining updates. Also if you're calling `Thread.sleep()` on the GUI thread, that's a big problem. C.f. "Low latency painting in Swing" https://pavelfatin.com/low-latency-painting-in-awt-and-swing/ – markspace May 08 '22 at 02:22
  • 2
    Swing is single threaded and not thread safe, this means, you shouldn't call any blocking operations on the Event Dispatching Thread and should not update the UI or it's state, from out of the Event Dispatching Thread. See [Concurrency in Swing](https://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html) for more details and [How to Use Swing Timers](https://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html) for the solution – MadProgrammer May 08 '22 at 02:38
  • For [example](https://stackoverflow.com/questions/54393447/make-animation-more-smoother/54396190#54396190) and [example](https://stackoverflow.com/questions/27933159/how-to-draw-an-bufferedimage-to-a-jpanel/27933189#27933189) and [example](https://stackoverflow.com/questions/35472233/load-a-sprites-image-in-java/35472418#35472418) – MadProgrammer May 08 '22 at 02:43

0 Answers0