2014-10-03 19 views
1

前幾天我問了這個: How to have multiple instances on the screen of the same sprite at the same time with javafx2 部分解決了jewelsea的建議問題。如何避免對我的遊戲中的子彈造成'機槍'效應?

我現在有這個障礙:當一個鍵被按下來'發射'子彈,武器射擊子彈和機槍一樣快...... 我想限制我的英雄武器的子彈數量遊戲可以拍攝..例如,決定每0.5秒發射一顆子彈,或者只是當按下一個按鍵時,不要一直有機槍效應...... 在我的遊戲中,控制'火'效果的程序部分是這樣的:

 scene.setOnKeyTyped(new EventHandler<KeyEvent>() { 
      @Override 
      public void handle(KeyEvent event2) { 

      if (event2.getCode()==KeyCode.F); { ......... 

我已經試過之前也使用setOnKeyPressed並具有相同的結果setOnKeyReleased .. 所以我可以嘗試拍攝只是一個子彈還保持按什麼'F'鍵還是限制子彈編號? 先謝謝你,再見!

+0

好的,我認爲的替代方案是:限制子彈的數量(如果你向距離牆壁較近的東西射擊,它們會更快地射擊),只檢測事件關鍵,靜音在彈出子彈後一段時間(使用計時器)的代碼...但我只是猜測,因爲我不知道javafx。 – Elric 2014-10-04 04:44:02

回答

0

我用Timeline作爲一個計時器,並啓動它,並停止其在關鍵按下並釋放鍵做到了這一點:

import javafx.animation.Animation; 
import javafx.animation.KeyFrame; 
import javafx.animation.Timeline; 
import javafx.application.Application; 
import javafx.scene.Scene; 
import javafx.scene.input.KeyCode; 
import javafx.scene.layout.Pane; 
import javafx.stage.Stage; 
import javafx.util.Duration; 

public class KeyEventTest extends Application { 

    @Override 
    public void start(Stage primaryStage) { 
     Pane root = new Pane(); 
     Scene scene = new Scene(root, 400, 400); 

     Duration firingInterval = Duration.millis(500); 
     Timeline firing = new Timeline(
       new KeyFrame(Duration.ZERO, event -> fire()), 
       new KeyFrame(firingInterval)); 
     firing.setCycleCount(Animation.INDEFINITE); 

     scene.setOnKeyPressed(event -> { 
      if (event.getCode() == KeyCode.F && firing.getStatus() != Animation.Status.RUNNING) { 
       firing.playFromStart(); 
      } 
     }); 

     scene.setOnKeyReleased(event -> { 
      if (event.getCode() == KeyCode.F) { 
       firing.stop(); 
      } 
     }); 

     primaryStage.setScene(scene); 
     primaryStage.show(); 
    } 

    private void fire() { 
     // dummy implementation: 
     System.out.println("Fire!"); 
    } 

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

這是相當容易適應這個額外限制對子彈的數量在任何時間的屏幕等。