2017-03-21 94 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语句来获得相同的行为。