Java System.currentTimeMillis()保持重置
我正在尝试在我的插口插件中创建一个冷却实用程序:Java System.currentTimeMillis()保持重置,java,minecraft,Java,Minecraft,我正在尝试在我的插口插件中创建一个冷却实用程序: package net.gettrillium.trillium.api.cooldown; import com.google.common.collect.HashBasedTable; import com.google.common.collect.Table; import net.gettrillium.trillium.Utils; import org.bukkit.Bukkit; import org.bukkit.entit
package net.gettrillium.trillium.api.cooldown;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
import net.gettrillium.trillium.Utils;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.util.UUID;
public class Cooldown {
private static Table<UUID, CooldownType, Long> cooldown = HashBasedTable.create();
public static void setCooldown(Player p, CooldownType type) {
cooldown.put(p.getUniqueId(), type, System.currentTimeMillis());
}
public static boolean hasCooldown(Player p, CooldownType type) {
if (cooldown.contains(p.getUniqueId(), type)) {
Bukkit.broadcastMessage("GET: " + cooldown.get(p.getUniqueId(), type));
Bukkit.broadcastMessage("CURRENT MILLIS: " + System.currentTimeMillis());
Bukkit.broadcastMessage("SUBTRACTED: " + (System.currentTimeMillis() - cooldown.get(p.getUniqueId(), type)));
Bukkit.broadcastMessage("IN SECONDS: " + (System.currentTimeMillis() - cooldown.get(p.getUniqueId(), type)) / 1000.0);
Bukkit.broadcastMessage("> WITH: " + (type.getTimeInTicks() / 20));
Bukkit.broadcastMessage("HAS COOLDOWN: " + (((System.currentTimeMillis() - cooldown.get(p.getUniqueId(), type)) / 1000.0) > (type.getTimeInTicks() / 20)));
if (((System.currentTimeMillis() - cooldown.get(p.getUniqueId(), type)) / 1000.0) > (type.getTimeInTicks() / 20)) {
return true;
} else {
cooldown.remove(p.getUniqueId(), type);
return false;
}
} else {
return false;
}
}
public static String getTime(Player p, CooldownType type) {
if (hasCooldown(p, type)) {
return Utils.timeToString((int) ((System.currentTimeMillis() - cooldown.get(p.getUniqueId(), type)) / 1000.0));
} else {
return null;
}
}
}
有人能解释为什么吗?这是
hasCooldown()中的一个简单逻辑错误。您可以从调试输出中看到,即使以秒为单位的时间小于冷却时间长度,它也会返回false
进行冷却
您可以通过在计算中使用临时变量了解为什么更容易。当您在地图中找到一个条目时,您正在执行以下等效操作:
long startMillis = cooldown.get(p.getUniqueId(), type);
double elapsedSecs = (System.currentTimeMillis() - startMillis) / 1000.0;
long cooldownSecs = type.getTimeInTicks() / 20;
boolean hasCooldown = elapsedSecs > cooldownSecs // wrong!
这是向后的:如果elapsedSecs>cooldownSecs
,则冷却已超时。如果cooldownSecs
,冷却仍然有效
因此,当elapsedSecs
时,hasCooldown()
错误地认为冷却已超时,因此它将其删除并返回false
。我确信您代码的其他部分没有找到冷却时间,会插入一个新的冷却时间,这就是为什么您会看到一个新的冷却时间。在hasCooldown()
中,您的逻辑一定有问题:如果在冷却时间设置后过早调用该方法,则返回false
,并删除现有条目。如果在设置后太长时间调用它,您是否打算这样做?也许你有一个,如果语句倒转了?setCooldown在哪里被调用?@DanGetz更新帖子:您可以包括调试输出吗?
long startMillis = cooldown.get(p.getUniqueId(), type);
double elapsedSecs = (System.currentTimeMillis() - startMillis) / 1000.0;
long cooldownSecs = type.getTimeInTicks() / 20;
boolean hasCooldown = elapsedSecs > cooldownSecs // wrong!