timer - 创建一个简单的处理倒计时

标签 timer processing countdown intervals

我在谷歌上搜索了很多网站,试图让它发挥作用,但似乎没有人在任何地方都有这个功能,如果他们这样做了,那就无法与我的程序一起工作......我想要实现的是让玩家有一个后坐力,当玩家被击中时,他在第一次被击中和第二次被击中之间有“x”的时间。

所以我有一个 bool 值“hit”= false,当他被击中时,它会变为true。这意味着他不能再次被击中,直到它再次变为 false。

因此,我尝试在程序中设置一个函数,为“x”秒数设置一个“计时器”IF hit = true,一旦该计时器达到“x”秒数,秒,hit 将切换回 false。

大家有什么想法吗?

谢谢!!

最佳答案

一个简单的选择是使用 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
  }
}

这里有一个细微的变化,更新屏幕上的“针”:

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);
}

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

如果您有兴趣使用 Java 的实用程序,正如 FrankieTheKneeMan 所建议的那样,有一个 TimerTask可用的类(class),我确信那里有大量的资源/示例。

您可以运行以下演示:

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);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.4.4/p5.min.js"></script>

关于timer - 创建一个简单的处理倒计时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12417937/

相关文章:

image - Kinect,使用深度图像获取Z值

jquery - 倒数计时器到期后重新启动

swift - 有人会解释这个处理 Timer.scheduledTimer(withTimeInterval : repeats: block:{})

javascript - 如何将秒转换为分秒?

java - 每天定时运行一个Java方法

Cocoa Touch - 倒计时器

javascript - 达到目标时更改倒数计时器的外观?

android - 抓取 GPS 数据的好地方在哪里?

audio - 调试脚本

arrays - 通过串口将长数组从处理发送到arduino