swing 飞机大战 二 实现地图的滚动

我的想法是先创建一个,保存图片和y坐标,主要就是靠画图片的y坐标来制造地图向下移动的感觉

创建地图类,4张背景图片可供选择

public class Map{
	public int y;
	public ImageIcon img1;
	public ImageIcon img2;
	public ImageIcon img3;
	public ImageIcon img4;
	public Map(int y){
		this.y = y;
		img1 = new ImageIcon("img/bj-1.jpg");
		img2 = new ImageIcon("img/bj-2.jpg");
		img3 = new ImageIcon("img/bj-3.jpg");
		img4 = new ImageIcon("img/bj-4.jpg");
	}
}
在创建地图对象,需要两个对象,轮换刷图,当一个向下滚动看不见后,就将它的y坐标改成负的,通过线程,增加y值

package pass;

import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JPanel;

import Game.FoeFly;
import Game.Map;
import Game.MyFly;

/**
 * 
 * @author Administrator
 *关卡类,
 */
public class No1 { //初始化面板
	PanelNo1 mp;
	public No1(JFrame jf){
		mp = new PanelNo1();
		jf.add(mp);
		jf.setSize(400, 600);
		mp.setBounds(0, 0, 500, 600);
	}
}
class PanelNo1 extends JPanel implements Runnable{
	MyFly myfly;
	Vector foefly;
	Vector imgarr;
	public PanelNo1() {
		myfly = new MyFly(240, 500, 100, true);
		foefly = new Vector<>();
		imgarr = new Vector<>();
		imgarr.add(new Map(0));
		imgarr.add(new Map(-600)); //初始化地图位置
		new Thread(this).start();
		this.addMouseListener(new MouseAdapter() {
			public void mouseEntered(MouseEvent e){
				myfly.x = e.getX();
				myfly.y = e.getY();
				System.out.println(e.getX()+" "+e.getY());
			}
		});
	}
	public void paint(Graphics g){
		super.paint(g);
		//进行地图的绘制,和画飞机画子弹
		drawMap(g); //画地图
		drawMyFly(g); //画我的飞机
		drawMyBomb(g); //画自己的炸弹
		drawFoeFly(g); //敌人飞机
		drawFoeBomb(g); //敌人弹
		this.repaint();
	}
	public void drawMap(Graphics g){
		for (int i=0; i<2; i++){
			g.drawImage(imgarr.get(i).img1.getImage(), 0, imgarr.get(i).y, 400, 600 ,null);
			System.out.println(imgarr.get(i).y);
		}
	}
	public void drawMyFly(Graphics g){
		
	}
	public void drawMyBomb(Graphics g){
		
	}
	public void drawFoeFly(Graphics g){
		
	}
	public void drawFoeBomb(Graphics g){
		
	}
	@Override
	public void run() {
		while (true){
			try {
				Thread.sleep(10);
			} catch (Exception e) {
				e.printStackTrace();
			}
			for (int i=0; i<2; i++){ //刷新地图
				imgarr.get(i).y += 1;
				if (imgarr.get(i).y >= 600){
					imgarr.get(i).y = -599; //轮换交替
				}
			}
		}
	}
}


你可能感兴趣的:(swing,飞机大战)