【问题标题】:How to use timer for scoring in Android?如何在 Android 中使用计时器进行计分?
【发布时间】:2012-09-28 01:28:56
【问题描述】:

我打算使用一个可见的计时器,它会从 30 秒倒计时到 0 秒。这个计时器将作为我的游戏应用程序中得分的基础,因为每次触摸移动的精灵(包含一个数字)但与请求的数字不匹配(如窗口/通知中所示),当前剩余时间将被扣除5 秒 (-5)。但是如果包含匹配数字的精灵被触摸,则计时器停止并且游戏重新开始(或移动到下一个级别)。

这是GameView 类中touchEvent 的代码:

@Override
   public boolean onTouchEvent(MotionEvent event) {
         if (System.currentTimeMillis() - lastClick > 300) {
                lastClick = System.currentTimeMillis();
                float x = event.getX();
                float y = event.getY();
                synchronized (getHolder()) {
                       for (int i = sprites.size() - 1; i >= 0; i--) {
                              Sprite sprite = sprites.get(i);
                              if (sprite.wasPopped(x, y)) {
                                    sprites.remove(sprite);
                                    spritePopped.add(new TempSprite(temps, this, x, y, pop));
                                    break;
                              }
                       }
                }
         }
         return true;
   }

每次触摸移动精灵周围的区域 (sprite.wasPopped) 时,都会将其从屏幕上移除(以及从分配的列表中删除),随后会出现一个图像 (spritePopped) 以指示它被触摸的位置(为了增加效果)。如何为计时器创建一个单独的类并在我的GameView 中使用它? 到目前为止,我遇到过使用刻度来计分,它是根据在某个类中调用了多少 update() 事件来计时的。任何 cmets/建议都会非常有帮助。

【问题讨论】:

    标签: android timer scoring


    【解决方案1】:

    您可以使用TimerTask,但不建议这样做,因为由于不在您的主线程上运行,它可能会产生一些不良影响。

    您应该做的是获取deltaTime 并将其存储在一个变量中。

        private float displayedTime;
    
        Public void timer(){ //call in update()
          displayedTime += deltaTime;
      }
    

    然后你可以混合使用这个来获得完整的秒数或任何你喜欢的计时器。

    您不应在更新方法中使用任何类型的计数器来检查时间或添加延迟,因为这会对无法以全 FPS 运行游戏的设备产生不良影响。

    【讨论】:

    • 我一直使用滴答声作为评分的衡量标准,并将其放在替换精灵图像被触摸后的类中。 (场景:屏幕上的移动气泡,触摸时弹出并被弹出图像替换)。到目前为止,没有做太多事情。
    • 那么您的问题到底是什么?你想让代码做什么?
    【解决方案2】:

    我发现了一个类似的问题,这里的计时器是在一个单独的类中创建的:

    import android.os.CountDownTimer;
    import android.widget.TextView;
    
    public class MyCount extends CountDownTimer {
    static TextView timeDisplay;
    
    public MyCount(long millisInFuture, long countDownInterval) {
        super(millisInFuture, countDownInterval);
    }
    
    public void onFinish() {
        timeDisplay.setText("Time has ended. Game over.");
        //restart(); 
    }
    
    public void onTick(long millisUntilFinished) {
        timeDisplay.setText("Left: " + millisUntilFinished / 1000);
    }
    

    }

    然后在 GameView 类中的一个单独函数中调用它(一旦游戏开始就会启动):

    public void setTimer() { 
    timeDisplay = new TextView(this);
    this.setContentView(timeDisplay);
    MyCount counter = new MyCount(30000, 1000);
    counter.start();
    

    }

    【讨论】:

      猜你喜欢
      • 2019-05-18
      • 2012-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-29
      相关资源
      最近更新 更多