姬長信(Redy)

java – 游戏的无限背景


我正在研究一个Java项目来模拟直升机在一个框架中的飞行.直升机使用箭头键在屏幕上移动.我希望直升机能够无限移动,也就是说,当直升机到达框架的边缘时,背景应朝相反的方向移动,以产生无尽的地形效果.

这是我到目前为止的代码:

import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.*;

public class MainFrame extends JFrame
{
    private static int FRAME_WIDTH = 800;
    private static int FRAME_HEIGHT = 500;

    public MainFrame()
    {
        add(new AnotherBackground(FRAME_WIDTH, FRAME_HEIGHT));
        setTitle("Helicopter Background Test");
        setSize(FRAME_WIDTH,FRAME_HEIGHT);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }

    public static void main(String[] args)
    {
        new MainFrame();
    }
}

class AnotherBackground extends JPanel
{
private BufferedImage heliImage = null;
private BufferedImage backImage = null;

private int heliX = 0;
private int heliY = 0;

private int backX = 0;
private int backY = 0;

private int frameWidth = 0;
private int frameHeight = 0;

private int backWidth = 0;
private int backHeight = 0;

public AnotherBackground(int fWidth, int fHeight)
{
    frameWidth = fWidth;
    frameHeight = fHeight;

    this.setFocusable(true);
    this.addKeyListener(new HeliListener());

    try
    {
        heliImage = ImageIO.read(new URL("http://imageshack.us/a/img7/2133/helicopter2f.png"));
        // 2.7 Meg Crap that is a humungous image!  Substitute dummy.
        backImage = new BufferedImage(1918,1200,BufferedImage.TYPE_INT_RGB);
    }

    catch(IOException ex)
    {
        System.out.println("Problem durinng loading heli image");
    }

    backWidth = backImage.getWidth();
    backHeight = backImage.getHeight();

    HeliPainter l = new HeliPainter();
    new Thread(l).start();
}

@Override
protected void paintComponent(Graphics g)
{
    super.paintComponent(g);

    g.drawImage(backImage, backX, backY, null);
    g.drawImage(heliImage, heliX, heliY, null);

}

class HeliListener extends KeyAdapter
{
    @Override
    public void keyPressed(KeyEvent e)
    {
        System.out.println(heliX + " " + heliY + " " + backX + " " + backY);

        if (e.getKeyCode() == KeyEvent.VK_LEFT)
        {
            if(heliX > 0)
            {
                heliX -= 5;
            }

            else
            {
                backX += 5;
            }
        }

        else if (e.getKeyCode() == KeyEvent.VK_RIGHT)
        {
            if(heliX  0)
            {
                heliY -= 5;
            }

            else
            {
                backY += 5;
            }
        }

        else if (e.getKeyCode() == KeyEvent.VK_DOWN)
        {
            if(heliY 

现在代码中有两个图像.一个是小型直升机,另一个是大型(2.7兆)背景.他们在这里:

> background
> helicopter http://imageshack.us/a/img7/2133/helicopter2f.png

如何连续显示BG?