9

我在谷歌上搜索了很多网站,试图让它工作,但似乎没有人在任何地方都有这个,如果他们这样做,那只是不与我的程序一起工作......我想要实现的是拥有一个播放器回避当玩家被击中时,他在第一次和第二次被击中之间有“x”的时间。

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

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

有人有想法么?

谢谢!!

4

1 回答 1

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

这是屏幕上更新“针”的细微变化:

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类可用,我相信那里有很多资源/示例。

您可以运行以下演示:

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>

于 2012-09-14T09:25:21.810 回答