简体   繁体   中英

Moving Object with Keys Leaves a Trail

In my Java game, I have a player class which has a BufferedImage assigned to it from a sprite sheet. I've just added in KeyAdapters and KeyListeners which just move the player around the screen. However, when I do this, it leaves behind a trail of the image.

private void render() {
    BufferStrategy bs = this.getBufferStrategy();
    if(bs == null) {
        createBufferStrategy(3);
        return;
    }
    Graphics g = bs.getDrawGraphics();

    p.render(g); //p is the player object

    g.dispose();
    bs.show();
}

public static void main(String[] args) {
    Game game = new Game();
    game.setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
    game.setMinimumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
    game.setMaximumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));

    JFrame frame = new JFrame(game.TITLE);

    frame.add(game);

    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setResizable(false);
    frame.setVisible(true);

    game.start();

}

If I understand correctly, your issue might be that you have a background that seems like it keeps the last drawn things in it.

So I think that you need to re-paint the background when you move the image ..

Here is a reference to Graphics basics in Java with simple exampels

Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM