问题
I am trying to add a timer for power ups in my game. What I am trying to do is change a parameter (like jump height for example) after the player has collided with the power up box but it should only apply for 4 seconds. I have already written the collision coding and have added a random element to choose which power up is activated. I have also added a power up that will not use the timer (adding 1 to the score).
Searching google I found code using various methods like Gdx.graphics.getDeltaTime() and Timer.schedule but I can't seem to get them to work, maybe I am coding them incorrectly. I've been trying to use code like this but when using System.out.println(timeSinceCollision), I keep getting a constant value every time and it doesn't seem to be increasing.
float timeSinceCollision = 0;
timeSinceCollision += delta;
if(timeSinceCollision < 4f) {
// the action
} else {
// reset
}
回答1:
As I mentioned in my comment above, you can use the CountDownTimer class.
new CountDownTimer(4000, 4000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
isPoweredUp = false;
}
}.start();
回答2:
You are creating timeSinceCollision every time with value of 0 thats why it never increase.
Take a look at my function. the If condition will be true every 4 seconds.
final float TIME_SINCE_COLLISION = 4;
float timeSinceCollision = 0;
public void update(float delta) {
timeSinceCollision += delta;
if (timeSinceCollision >= TIME_SINCE_COLLISION) {
timeSinceCollision -= TIME_SINCE_COLLISION;
// Do something after 4 seconds.
Gdx.app.log("Do something", "");
}
}
来源:https://stackoverflow.com/questions/23859039/how-do-i-add-a-timer-in-libgdx-java