[英]How to use timer for scoring in Android?
我打算使用一个可见的计时器,该计时器将从30秒倒计时到0秒。 此计时器将成为我的游戏应用程序评分的基础,因为每次触摸移动的精灵(包含数字)但与请求的数字不匹配(如窗口/通知中所示)时,都会扣除当前剩余时间5秒(-5)。 但是,如果触摸了包含匹配编号的精灵,计时器将停止并重新开始游戏(或移至下一个级别)。
下面是该代码touchEvent
里面GameView
类:
@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
显示图像( spritePopped
)以指示已触摸的位置(以增强效果)。 。 如何为计时器创建单独的类并在GameView
使用它? 到目前为止,我遇到了使用滴答声进行评分的方法,该评分是根据某个类中调用了多少update()
事件来计时的。 任何意见/建议都将非常有帮助。
您可以使用TimerTask
但不建议这样做,因为由于未在主线程上运行,它可能会产生一些不良影响。
您应该做的是获取deltaTime
并将其存储在变量中。
private float displayedTime;
Public void timer(){ //call in update()
displayedTime += deltaTime;
}
然后,您可以与此混合使用以获得完整的秒数或您喜欢的任何计时器。
您不应在更新方法中使用任何类型的计数器来检查时间或增加延迟,因为这会对无法以完整FPS运行游戏的设备产生不良影响。
我发现了与此类似的问题,在这里计时器是在单独的类中创建的:
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.