Java a moving animation (sprite)

↘锁芯ラ 提交于 2019-12-05 20:52:57

Your loop looks a bit incorrect

       Graphics2D g = s.getGraphics();  
      while(cumTime - startingTime < 5000) {
        long timePassed = System.currentTimeMillis() - cumTime;
        cumTime += timePassed;
        update(timePassed);

        //draw and update the screen
        draw(g);
        g.dispose();
        s.update();

        try{
            Thread.sleep(20);
        }catch(Exception ex) {
            System.err.println("Error: " + ex);
        }
    }
}

also try this for your draw method.

// Graphics with new function
public void draw(Graphics g) {
    g.clearRect(0,0,800,600);
    g.drawImage(sprite.getImage(), Math.round(sprite.getX()), Math.round(sprite.getY()), null);
}

clearRect goes before drawImage.

I also had a problem with this and you need a "do while loop" in stead of while loop like this:

do{
        Graphics2D g = s.getGraphics();
        long timePassed = System.currentTimeMillis() - cumTime;
        cumTime += timePassed;
        update(timePassed);


        //draw and update
        draw(g);
        g.dispose();
        s.update();

        try{
            Thread.sleep(20);
        }catch(Exception ex){
            System.out.println("Can't sleep :(");
        }
    }
    while(cumTime - startingTime < 20000); //the Time

And the clearRect must be ABOVE the drawImage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!