在处理中创建一个简单的倒计时

D34*_*ker 9 processing timer intervals countdown

我已经搜索了Google上的这么多网站试图让它工作但是没有人似乎在任何地方都有这个,如果他们这样做只是不使用我的程序......我想要实现的是拥有一个玩家当玩家被击中时,他在第一次和第二次击中之间有一段"x"的时间.

所以我有一个Boolean "hit" = false,当他被击中时,它会改变true.这意味着他再次被击中,直到它再次变为假.

所以我试图在我的程序中设置一个函数来设置"x"秒的"计时器" IF hit = true,一旦该计时器达到"x"秒的数量,命中将被切换回假.

有人有主意吗?

谢谢!!

Geo*_*nza 15

一个简单的选择是使用millis()手动跟踪时间.

您将使用两个变量:

  1. 一个存储已用时间
  2. 一个存储您需要的等待/延迟时间

在draw()方法中,您将检查当前时间(以毫秒为单位)与先前存储的时间之间的差异是否大于(或等于)延迟.

如果是这样的话,那么你就可以提供任何延迟,并更新存储的时间:

int time;
int wait = 1000;

void setup(){
  time = millis();//store the current time
}
void draw(){
  //check the difference between now and the previously stored time is greater than the wait interval
  if(millis() - time >= wait){
    println("tick");//if it is, do something
    time = millis();//also update the stored time
  }
}
Run Code Online (Sandbox Code Playgroud)

这是在屏幕上更新"针"的轻微变化:

int time;
int wait = 1000;

boolean tick;

void setup(){
  time = millis();//store the current time
  smooth();
  strokeWeight(3);
}
void draw(){
  //check the difference between now and the previously stored time is greater than the wait interval
  if(millis() - time >= wait){
    tick = !tick;//if it is, do something
    time = millis();//also update the stored time
  }
  //draw a visual cue
  background(255);
  line(50,10,tick ? 10 : 90,90);
}
Run Code Online (Sandbox Code Playgroud)

根据您的设置/需求,您可以选择将类似这样的内容包装到可以重复使用的类中.这是一种基本方法,也应该适用于Android和JavaScript版本(尽管在javascript中你有setInterval()).

如果您对使用Java的实用程序感兴趣,就像FrankieTheKneeMan建议的那样,有一个TimerTask类可用,我确信有很多资源/示例.

您可以运行以下演示:

var time;
var wait = 1000;

var tick = false;

function setup(){
  time = millis();//store the current time
  smooth();
  strokeWeight(3);
}
function draw(){
  //check the difference between now and the previously stored time is greater than the wait interval
  if(millis() - time >= wait){
    tick = !tick;//if it is, do something
    time = millis();//also update the stored time
  }
  //draw a visual cue
  background(255);
  line(50,10,tick ? 10 : 90,90);
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.4.4/p5.min.js"></script>
Run Code Online (Sandbox Code Playgroud)

更新有许多方法可以制作计时器.这是一个使用Thread的版本,并按名称调用草图中定义的函数.这不是一个简单的倒计时.millis()如上所述直接上升很简单,只是不太灵活:

Timer timer;

void setup(){
  noStroke();

  //textSize(12);
  timer = new Timer(this,"onTimerTick","onTimerComplete");
  // start a timer for 10 seconds (10 * 1000 ms) with a tick every second (1000 ms) 
  timer.reset(10 * 1000,1000);
}

void draw(){
  background(0);
  drawTimer();
  //rect(0,0,timer.progress * width,height);
  //blendMode(DIFFERENCE);
  text("'1' = reset"+
     "\n'2' = cancel"+
     "\n'3' = pause"+
     "\n'4' = resume"+
     "\n"+(int)(timer.progress * 100)+"%",10,15);
}

void drawTimer(){
  pushStyle();
  noFill();
  stroke(255);
  strokeWeight(3);
  ellipse(450, 54,90,90);
  fill(192,0,0);
  noStroke();
  pushMatrix();
  translate(50,50);
  rotate(radians(-90));
  arc(0, 0, 90, 90, 0, timer.progress * TWO_PI, PIE);
  popMatrix();
  popStyle();
}

void keyPressed(){
  if(key == '1'){
    timer.reset(3000,10);
  }
  if(key == '2'){
    timer.cancel();
  }
  if(key == '3'){
    timer.pause();
  }
  if(key == '4'){
    timer.resume();
  }
}

public void onTimerTick(){
  println("tick",(int)(timer.progress * 100),"%");
}

public void onTimerComplete(){
  println("complete");
}

import java.lang.reflect.Method;
// utility timer class
class Timer implements Runnable{
  // is the timer still ticking or on hold ?
  boolean isPaused = false;
  // is the thread still running ?
  boolean isRunning = true;

  // how close are we to completion (0.0 = 0 %, 1.0 = 100%)
  float progress = 0.0;
  // a reference to the time in ms since the start of the timer or reset
  long now;
  // default duration
  long duration = 10000;
  // default tick interval
  long tickInterval = 1000;
  // time at pause
  long pauseTime;

  // reference to the main sketch
  PApplet parent;
  // function to call on each tick
  Method onTick;
  // function to call when timer has completed
  Method onComplete;

  Timer(PApplet parent,String onTickFunctionName,String onCompleteFunctionName){
    this.parent = parent;
    // try to store a reference to the tick function based on its name
    try{
      onTick = parent.getClass().getMethod(onTickFunctionName);
    }catch(Exception e){
      e.printStackTrace();
    }

    // try to store a reference to the complete function based on its name
    try{
      onComplete = parent.getClass().getMethod(onCompleteFunctionName);
    }catch(Exception e){
      e.printStackTrace();
    }
    // auto-pause
    isPaused = true;
    // get millis since the start of the program
    now = System.currentTimeMillis();
    // start the thread (processes run())
    new Thread(this).start();
  }

  // start a new stop watch with new settings
  void reset(long newDuration,long newInterval){
    duration = newDuration;
    tickInterval = newInterval;
    now = System.currentTimeMillis();
    progress = 0;
    isPaused = false;
    println("resetting for ",newDuration,"ticking every",newInterval);
  } 

  // cancel an existing timer
  void cancel(){
    isPaused = true;
    progress = 0.0;
  }

  // stop this thread
  void stop(){
    isRunning = false;
  }

  void pause(){
    isPaused = true;
    pauseTime = (System.currentTimeMillis() - now); 
  }
  void resume(){
    now = System.currentTimeMillis() - pauseTime;
    isPaused = false;
  }

  public void run(){
    while(isRunning){

      try{
          //sleep per tick interval
          Thread.sleep(tickInterval);
          // if we're still going
          if(!isPaused){
            // get the current millis
            final long millis = System.currentTimeMillis();
            // update how far we're into this duration
            progress = ((millis - now) / (float)duration);
            // call the tick function
            if(onTick != null){
              try{
                onTick.invoke(parent);
              }catch(Exception e){
                e.printStackTrace();
              }
            }
            // if we've made, pause the timer and call on complete
            if(progress >= 1.0){
              isPaused = true;
              // call on complete
              if(onComplete != null){
              try{
                  onComplete.invoke(parent);
                }catch(Exception e){
                  e.printStackTrace();
                }
              }
            }
          }
        }catch(InterruptedException e){
          println(e.getMessage());
        }
      }
    }

}
Run Code Online (Sandbox Code Playgroud)

螺纹计时器演示草图预览:根据时间进度将圆弧变成圆形

另外,您可以使用Java的TimerTask 类.