I'm making a game in java and need to paint units on a gameboard. I put all units in a list and paints every unit in that list. The paint method looks like this:
public void paint(Graphics g) {
super.paint(g);
if (unitList != null) {
Collections.sort(unitList);
for (Unit unit : unitList) {
Image image = unit.getImage();
g.drawImage(
image,
(int) (playPosition.x + unit.getPosition().getX() - image
.getWidth(null) / 2), (int) (playPosition.y
+ unit.getPosition().getY() - image
.getHeight(null) / 2), null);
}
}
}
I have tried to make a BufferStrategy but it only makes the problem worse, guess I am doing something wrong.
Thanks
Maybe you haven't implemented BufferStrategy
correctly.
Try manual double buffering by doing offscreen painting on an Image
, and then just paint the whole said image in your regular overriden paint()
method.
You would do that like so:
// Double buffering objects.
Image doubleBufferImage;
Graphics doubleBufferGraphics;
/*
* Onscreen rendering.
*/
@Override
public void paint(Graphics g) {
doubleBufferImage = createImage(getWidth(), getHeight());
doubleBufferGraphics = doubleBufferImage.getGraphics();
paintStuff(doubleBufferGraphics);
g.drawImage(doubleBufferImage, 0, 0, this);
}
/*
* Offscreen rendering.
*/
public void paintStuff(Graphics g) {
if (unitList != null) {
Collections.sort(unitList);
for (Unit unit : unitList) {
Image image = unit.getImage();
g.drawImage(
image,
(int) (playPosition.x + unit.getPosition().getX() - image
.getWidth(null) / 2), (int) (playPosition.y
+ unit.getPosition().getY() - image
.getHeight(null) / 2), null);
}
}
}
来源:https://stackoverflow.com/questions/13858802/flickering-images-in-java-bufferstrategy