我需要让我的游戏背景移到了所有的时间..滚动背景,JAVA
我知道我需要使用一些线程添加变量“Y”图像坐标
我试图做一些事情,但是当它开始将所有的后台得到某种原因裸奔,不能理解为什么...
public class Background {
private BufferedImage image;
.....
....
public Background(int x, int y) {
this.x = x;
this.y = y;
// Try to open the image file background.png
try {
BufferedImageLoader loader = new BufferedImageLoader();
image = loader.loadImage("/backSpace.png");
}
catch (Exception e) { System.out.println(e); }
}
/**
* Method that draws the image onto the Graphics object passed
* @param window
*/
public void draw(Graphics window) {
// Draw the image onto the Graphics reference
window.drawImage(image, getX(), getY(), image.getWidth(), image.getHeight(), null);
// Move the x position left for next time
this.y +=1 ;
}
public class ScrollingBackground extends Canvas implements Runnable {
// Two copies of the background image to scroll
private Background backOne;
private Background backTwo;
private BufferedImage back;
public ScrollingBackground() {
backOne = new Background();
backTwo = new Background(backOne.getImageWidth(), 0);
new Thread(this).start();
setVisible(true);
}
@Override
public void run() {
try {
while (true) {
Thread.currentThread().sleep(5);
repaint();
}
}
catch (Exception e) {}
}
@Override
public void update(Graphics window) {
paint(window);
}
public void paint(Graphics window) {
Graphics2D twoD = (Graphics2D)window;
if (back == null)
back = (BufferedImage)(createImage(getWidth(), getHeight()));
Graphics buffer = back.createGraphics();
backOne.draw(buffer);
backTwo.draw(buffer);
twoD.drawImage(back, null, 0, 0);
}
你是什么意思是“裸奔” –
我编辑的问题,增加的态势图。)你也许不应该调用重绘(的 – user2922456
首先,它真正的意思内部使用。其次,您看到裸奔的原因是因为图形区域未被清除是因为手动调用重新绘制可以防止您的画布被清除。你应该使用update()。 –