【问题标题】:Scrolling background, JAVA滚动背景,JAVA
【发布时间】:2014-06-15 16:16:25
【问题描述】:

我需要让我在游戏中的背景一直上升..

我知道我需要使用一些线程将变量添加到图像的 'y' 坐标

我试图做某事,但当它开始移动时,所有背景都因某种原因出现条纹,无法理解为什么......

图片:streaking background

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);

}

【问题讨论】:

  • “裸奔”是什么意思
  • 我编辑问题并添加情况图片..
  • 首先你可能不应该调用repaint(),它实际上是为了内部使用。其次,您看到条纹的原因是因为图形区域没有被清除是因为手动调用 repaint 可以防止您的画布被清除。您应该改用 update()。
  • 试试直接调用paint方法?
  • 1) 为了尽快获得更好的帮助,请发布MCVE(最小完整且可验证的示例)。 2) 例如,获取图像的一种方法是热链接到this answer 中看到的图像。

标签: java canvas awt thread-sleep


【解决方案1】:

你不需要一个新线程,这只是在这种情况下使事情变得过于复杂。 您只需要继续在背景的 Y 坐标上添加一个因子。 例如:

float scrollFactor = 0.5f; //Moves the background 0.5 pixels up per call of the draw method

public void draw(Graphics window) {

    window.drawImage(image, getX(), getY(), image.getWidth(), image.getHeight(), null);

    this.y += scrollFactor;
}

【讨论】:

  • 所以你告诉我我的第二节课不需要?
  • 您不需要背景类中的第二个线程,只需从主游戏线程调用背景类的绘制方法即可。
  • @user2922456 是的,完全正确。
  • 嗯..应该。您能否将吸气剂添加到您的问题中?
  • 我不需要将两个图片加载到缓冲区中吗?图片在一些'y'中结束了......不是吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-21
相关资源
最近更新 更多