0
我已經能夠讓我的飛船拍攝一個lazer物體,並且一旦lazer離開屏幕,它只是將物體重置到原始位置,但是我想讓lazer物體在我可以再次射擊之前不要依賴脫屏。那麼,每當按下向上鍵時,我怎麼讓我的飛船拍攝拉澤爾?換句話說,每次按下按鍵並拍攝它時都會創建一個新的lazer物體,而不是一次又一次重置一個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;
}}
你自己試圖解決這個問題的地方在哪裏?此代碼沒有看起來像它試圖在按鍵上創建一個新對象 – UnholySheep
我創建了lazer 1,2和3,然後將它們放入一個數組中,並嘗試在我的tick方法中逐一訪問它們。我已經嘗試了很多不同的方式來正確地做到這一點,但幾天之後一直未能找到答案。 – sk8yard