2017-03-21 95 views
0

的答案 - 賽車條件布爾不改變

所以這是遊戲我做產生的障礙,每個障礙熄滅屏幕它消除了障礙,增加了高分時間的類。這工作正常,但布爾(plusScore)在預期時不會更改爲true。

public void update() { 
      // 
      if(obstacles.get(obstacles.size() - 1).getRectangle().top >= Constants.SCREEN_HEIGHT) { 
       int xStart = (int)(Math.random()*(Constants.SCREEN_WIDTH - playerGap)); 
       obstacles.add(0, new Obstacle(obstacleHeight, color, xStart, obstacles.get(0).getRectangle().top - obstacleHeight - obstacleGap, playerGap)); 
       obstacles.remove(obstacles.size() - 1); 
       score += 10; 
       plusScore = true; //Problem here 
       tempTime = (int)System.currentTimeMillis(); 
      } 
      if (tempTime + 5 <= System.currentTimeMillis()) { 
       plusScore = false; //Unsure if working as relying on above 
      } 
     } 

這(下)在這裏,我呼籲布爾,我包括方法的第一部分,我不知道是否有可能是可能發生的衝突。

public void draw(Canvas canvas) { 
    for(Obstacle ob : obstacles) 
     ob.draw(canvas); 
    Paint paint = new Paint(); 
    paint.setTextSize(100); 
    paint.setColor(Color.BLACK); 
    canvas.drawText(" " + score, 50, 50 + paint.descent() - paint.ascent(), paint); 

    if(plusScore) { //This is what the Boolean should effect 
     Paint paint2 = new Paint(); 
     paint2.setTextSize(100); 
     paint2.setColor(Color.GREEN); 
     drawPlusScore(canvas, paint2, "+10!"); 
    } 
} 

[我想弄清楚的時候沒有平局方法工作正常,如果聲明] 如果問題很明顯我很抱歉,我在下面的第一次的教程,並決定嘗試一些我自己。

+0

滿足以下條件:obstacle.get(barriers.size() - 1).getRectangle()。top> = Constants.SCREEN_HEIGHT –

+0

是的,它每次離開屏幕時都會將分數提高10已經在模擬器中檢查過) – George

+0

我懷疑賽車狀況。試着重置'draw'中的布爾值而不是'update' - > put'plusScore = false;'作爲'if(plusScore)'中的第一個語句。在不同的線程上調用'update'和'draw'?如果是這樣,儘量讓它變得不穩定。 – Fildor

回答

1

我看到兩種可能性:

  1. 您的系統足夠慢,在update()方法設置,布爾在第一if後,你在第二if土地和您的變量設置爲false(我覺得這不太可能,但如果你在某種模擬器中運行,也許?)。可能值得使用某些日誌記錄來確認繪圖是在將此變量設置爲true和false之間發生的。

  2. 您的update()方法中的plusScore變量與draw()方法中的plusScore變量不同。這兩種方法都在同一個類中嗎?我可以告訴你的plusScore變量是你的代碼片段中的一個字段,但如果這兩個代碼片段不在同一個類中,那麼你正在處理兩個完全分離的變量。

1

您的plusScore將在每次調用update時設置爲false。試試這個:

public class CheckTime { 
    public static void main(String []args){ 
     int tempTime = (int) System.currentTimeMillis(); 
     long longTime = System.currentTimeMillis(); 
     System.out.println("As long: " + longTime); 
     System.out.println("As int: " + tempTime); 
     System.out.println("Check: " + (tempTime + 5 < longTime)); 
    } 
} 

輸出是:

As long: 1490102795366 
As int: -250856346 
Check: true 

這意味着:因爲你是鑄造當前時間從longint你得到溢出。這就是爲什麼你最後一條if語句在update將永遠是真實的。

你應該儘量避免比較兩種不同的類型,如intlong(除非你110%確定它是相同的,但你應該能夠使用相同的類型)。長時間更改tempTime,刪除演員陣容,它將起作用。

另一個提示:plusScoretempTime + 5 <= System.currentTimeMillis()在本例中具有相同的語義。因此,您可以擺脫plusScore,並使用draw中的update的if語句來獲得相同的行爲。