我看过动画,它们通常看起来很光滑/干净,但是当我看到它时,它们似乎有鬼影或尾巴。他们似乎也更加狡猾。我不知道是什么原因造成的,我不知道如何解决它。我不知道这是因为我的游戏循环还是我的绘画方法。
Here is a short (Super Short) video of what it looks like
当我看到其他游戏项目移动非常好时,我该如何实现?
@Override
public void paint(Graphics g){
this.dbImage = createImage(this.getWidth(), this.getHeight());
this.dbg = dbImage.getGraphics();
this.paintComponent(dbg);
g.drawImage(this.dbImage, 0, 0, this);
}
/**
*
* @param g
*
* Draws out all of the GameObjects in the room
*/
@Override
public void paintComponent(Graphics g){
try{
g.drawImage(bg, 0, 0, this);
for(GameObject go : this.gameObjects){
g.drawImage(go.getSprite(), go.getX(), go.getY(), this);
}
//this.repaint();
}catch(Exception e){
}
}
这没有paint()
方法:
答案 0 :(得分:0)
这是我写它的方式。评论解释了这个过程。
//in constructor, and whenever your component resizes
this.dbImage = createImage(this.getWidth(), this.getHeight());
@Override
public void paint(Graphics g){
//probably shouldn't have a class instance of graphics.
Graphics2D dbg = dbImage.createGraphics();
//clear offscreen buffer image.
dbg.fillRectangle(0,0,dbImage.getWidth(),dbImage.getHeight());
//render a new frame to offscreen buffer
this.paintComponent(dbg);
//render offscreen buffer to component
g.drawImage(this.dbImage, 0, 0, this);
gdb.dispose();
}
编辑:
以下是清除组件屏幕的方法。
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
//alternatively, g.fillRectangle(0,0,getWidth(),getHeight());
try{
g.drawImage(bg, 0, 0, this);
for(GameObject go : this.gameObjects){
g.drawImage(go.getSprite(), go.getX(), go.getY(), this);
}
//this.repaint();
}catch(Exception e){
}
}
您发布的屏幕截图看起来就像是要么没有清除JComponent,要么就是没有清除屏幕外缓冲区dbImage
。
答案 1 :(得分:0)
有一种称为双缓冲的技术可以使动画看起来更流畅。以下是如何操作的示例:
声明BufferedImage类型的字段:
BufferedImage backbuffer
创建双缓冲区:
backbuffer = new BufferedImage(screenWidth, screenHeight, BufferedImage.TYPE_INT_RGB);
使用BufferedImage提供的图形绘制视图:
g2d = backbuffer.createGraphics();
g2d.drawImage(...);
希望有所帮助。