我已经能够让我的太空飞船射击一个激光对象,一旦激光器离开屏幕,它就会将物体重置到原始位置,但是我想让激光对象不依赖于屏幕之前我可以再拍。那么每次按下向上键时,如何让我的飞船射击?换句话说,每按一次键就会创建一个新的lazer对象并进行拍摄,而不必一遍又一遍地重置一个激光对象。
public class Game extends Canvas implements Runnable {
private static final long serialVersionUID = 5794099463789882206L;
public static final int WIDTH = 1300, HEIGHT = 700;
private Thread thread;
private boolean running = false;
private Random ra;
private Handler handler;
public static int posX = 368;
public static int posY = 500;
private HUD hud;
private Laz lazer;
private Laz lazer1;
private Laz lazer2;
private Laz[] laz;
private static int in;
public Game(){
new Window(WIDTH, HEIGHT, "LEGGO SPAGHETTIO", this);
handler = new Handler();
this.addKeyListener(new KeyInput(handler));
ra = new Random();
hud = new HUD();
for(int i = 0; i<300; i++){
handler.addObject(new Player2(ra.nextInt(WIDTH), ra.nextInt(HEIGHT*5), ID.Player2));
}
lazer = new Laz();
lazer1 = new Laz();
lazer2 = new Laz();
laz = new Laz[] {lazer, lazer1, lazer2};
handler.addObject(new Player(posX, posY, ID.Player));
//handler.addObject(new Lazer(posX, posY, ID.Lazer));
handler.addObject(new BasicEnemy(posX, posY, ID.BasicEnemy));
}
public synchronized void start(){
thread = new Thread(this);
thread.start();
running = true;
}
public synchronized void stop(){
try{
thread.join();
running = false;
}catch(Exception e){
e.printStackTrace();
}
}
public void run()
{
this.requestFocus();
long lastTime = System.nanoTime();
double amountOfTicks = 60.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
long timer = System.currentTimeMillis();
int frames = 0;
while(running)
{
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while(delta >=1)
{
tick();
delta--;
}
if(running)
render();
frames++;
if(System.currentTimeMillis() - timer > 1000)
{
timer += 1000;
// System.out.println("FPS: "+ frames);
frames = 0;
}
}
stop();
}
private void tick(){
handler.tick();
hud.tick();
if(KeyInput.up_key_pressed){
laz[in].shoot();
}
}
private void render(){
BufferStrategy bs = this.getBufferStrategy();
if (bs == null){
this.createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.black);
g.fillRect(0, 0, WIDTH, HEIGHT);
handler.render(g);
hud.render(g);
laz[in].render(g);
g.dispose();
bs.show();
}
public static void main(String args[]){
new Game();
}
}
public class Laz {
private int y = 650;
private int velY = 10;
public void tick(){
}
public void render(Graphics g){
g.fillRect(150, y, 20, 20);
g.setColor(Color.BLUE);
}
public void shoot(){
y-=velY;
}}
答案 0 :(得分:0)
您可以创建班级Laz的列表,然后在需要时添加新的Laz。然后,如果您需要在激光对象关闭之前实现一种能够访问激光对象的方法,以及在需要删除它们时从阵列列表中删除激光对象的方法