2012-05-29 62 views
1

我試圖讓球從窗口的頂部落下。我將球對象存儲在ArrayList中,此刻,我正在執行此操作。Java遊戲時機動作

for (int i = 0; i < balls.size(); i++) { 
    Ball b = (Ball) balls.get(i); 
    if (b.isVisible()) { 
     b.move(); 
    } 

移動功能只是改變球的y座標,因此它下降屏幕。

目前,它正在同時被完全同時畫,並在同一時間下降。

例如http://puu.sh/xsGF

我該如何使它們以隨機間隔落下?

我的move()函數如下。

public void move() { 

    if (y > 480) { 
     this.setVisible(false); 
     System.out.println("GONE"); 
    } 
    y += 1; 
} 
+0

您需要在每次移動後重新繪製球。 –

+0

這不是問題。我如何得到它,以便在不同的時間下降? – user432584920684

+1

在Ball.move()方法中,您需要對其速度應用一些隨機變化。沒有看到這一點,沒有辦法來幫助你。 – Tharwen

回答

0

有兩件事情可以做:

  1. 添加一個計時器。當定時器關閉時(例如每隔10毫秒),選擇一個隨機球,讓那個球落下1px。 ()注意,由於隨機因素,您將獲得在不同時間以不同速度下降的球。)

  2. 初始化球時使用隨機值作爲速度。通過該速度值增加y座標,所以球將通過場景以不同的速率下降。

1

您可以在遊戲循環中隨機添加球。

//add new balls randomly here: 
if(<randomtest>) { 
    balls.add(new Ball()); 
} 
for (int i = 0; i < balls.size(); i++) { 
    Ball b = (Ball) balls.get(i); 
    if (b.isVisible()) { 
     b.move(); 
    } 
    else { 
    //also might be good idea to tidy any invisible balls here 
    //if you do this make sure you reverse the for loop 
    } 
} 
+0

銀色的Java標記徽章附近;) – danihp

+1

@danihp應該這樣做,謝謝! – weston

0

最簡單的方法,如果你想等速,是將它們即時隨機位置putside視口的頂部。

因爲我猜你已經在屏幕之外繪製它們,只需在其中添加一個隨機位移,就完成了。例如:

ball.y = -radius + random.nextInt(100); 
0

好的,看到你的移動功能,這並不是真正的物理上的正確。你應該有一個加速。這會讓球落得更加逼真(當然還有空氣阻力等等,但我認爲現在已經足夠了)。爲了讓它們在隨機時間下降,你可以隨機添加它們(使它們在隨機時間點存在/可見)等等。

class Ball { 
    private double acc = 9.81; // or some other constant, depending on the framerate 
    private double velocity = 0; 
    private double startFallTime = Math.random()*100; // set from outside, not here! 

    public void move() { 
    // check if ball is already here 
    if (startFallTime-- > 0) return; 
    if (y > 480) { 
     this.setVisible(false); 
     System.out.println("GONE"); 
    } 
    velocity += acc; 
    y += velocity; 
    } 
} 

編輯:當然,加速的東西是可選的,這取決於你想要什麼。如果你想要線性運動,那麼你的方法很好,如果球有加速度,它看起來會更好。 ;)另外,我建議在隨機實例中添加球,而不是使用我使用的startFallTime,因爲這在物理上並不真正。雖然取決於你的需求,所以你必須自己找出正確的方法。