开发者

How to set something to happen after a certain amount of time?

I am programming a game right now for Android and I am running into the problem that when I collide with an enemy my health bar is sh开发者_如何学编程ooting straight down TOO fast.

I want to allow it to only register two hits every second. As of right now it seems like it goes through 50 frames of animation in 1-2 secs.

Please give me ideas of how I can solve my problem.

Thanks!


How about storing a timestamp when the last collision happened into your player object and compare the current time to it when collision is detected? If enough time has passed then reduce health. This way you are not bound to possible fluctuating frame rate.


The best solution to run something after a certain amountof time immo is to use a TimerTask. For example this code runs on 31. December 2011.

Timer timer = new Timer();
timer.schedule(new TimerTask( 

public void run() {

    System.out.println("done");

}),

new Date(2011, 12, 31));


Put the job into an AsyncTask, where the doInBackground() method is counting down, sends a progress update and then sleeps for a small time.

Pseudo code:

doInBackground(int howMuch) {
   while (howMuch > 0 ) {
       publishProgress(howMuch);
       Thread.sleep(1000 / howMuch);
  } 
}

onProgressUpdate(int current) {
     updateProgressBar(current);
}


might even be simpler to make a Runnable and make it flip a invincible flag to false when it fires.

mHandler = new Handler() (during onCreate)
notInvincible = true;

-- get damaged --
if(damaged && notInvincible ){
  notInvincible = false;
  mHandler.postDelayed(new Runnable(){ void run() { notInvincible = true; }},DELAYTIME);
}

but AsyncTask would also let you do this.


The usual method to do something like this is to count the frametime (the time since the last frame). With this time you can make all movements time dependent and also handle stuff like these timers.
For a collision like this you'd add a attribute to your player class with the time since the last hit. Every frame this attribute is added up with the frame time. You can then check the time since the last collision. After a hit you can set the timer back to zero. No threads involved.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜