我在谷歌上搜索了很多网站,试图让它发挥作用,但似乎没有人在任何地方都有这个功能,如果他们这样做了,那就无法与我的程序一起工作......我想要实现的是让玩家有一个后坐力,当玩家被击中时,他在第一次被击中和第二次被击中之间有“x”的时间。
所以我有一个 bool 值“hit”= false
,当他被击中时,它会变为true
。这意味着他不能再次被击中,直到它再次变为 false。
因此,我尝试在程序中设置一个函数,为“x”秒数设置一个“计时器”IF hit = true
,一旦该计时器达到“x”秒数,秒,hit 将切换回 false。
大家有什么想法吗?
谢谢!!
最佳答案
一个简单的选择是使用 millis() 手动跟踪时间.
您将使用两个变量:
- 用于存储耗时
- 用于存储您需要的等待/延迟时间
在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/