我正在使用BufferedImage
来获得平滑的图形(即没有闪烁)。然而,在中间绘制的正方形非常闪烁,有时实际上是不可见的。我不知道出了什么问题,这种方法在我的其他游戏中运行良好。
这是我的代码(Square是我定义的类型):
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
import java.applet.*;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
public class DodgeArrows extends Applet implements KeyListener,Runnable{
BufferedImage backbuffer;
Thread gameloop;
Square player;
Random r = new Random();
Graphics2D g2d;
AffineTransform trans = new AffineTransform();
public void init()
{
backbuffer = new BufferedImage(640,480,BufferedImage.TYPE_INT_RGB);
g2d = backbuffer.createGraphics();
player = new Square();
player.setX(320);
player.setY(480);
}
public void start()
{
gameloop = new Thread(this);
gameloop.start();
}
public void run()
{
Thread t = Thread.currentThread();
while(t==gameloop)
{
try
{
Thread.sleep(20);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
repaint();
}
}
public void stop()
{
gameloop = null;
}
public void update(Graphics g)
{
g2d = (Graphics2D)g;
g2d.setColor(Color.BLACK);
g2d.fillRect(0,0,getSize().width,getSize().height);
g2d.setColor(player.getColor());
g2d.fill(player.getShape());
paint(g);
}
public void keyTyped(KeyEvent e){}
public void keyPressed(KeyEvent e)
{
//irrelevant keylistener code
}
public void keyReleased(KeyEvent e){}
public void paint(Graphics g)
{
g.drawImage(backbuffer,0,0,this);
}
}
答案 0 :(得分:2)
从更新(...)方法中删除行g2d = (Graphics2D)g;
,您的所有问题都会消失。
您已在行g2d = backbuffer.createGraphics();
中创建了一个后备缓冲区。当您将g
分配给g2d
时,您正在使它们都引用相同的Graphics对象并丢弃您的缓冲区。您将回到直接绘制到屏幕上。