如果 variable.x 在 x 秒内 < 0.1 然后做某事,我该如何做呢?

How do I make an if that says if variable.x has been < 0.1 for x amount of seconds then do something?

尝试查找此问题,但这是一个很难搜索的问题。

所以如果说一个球在 1 或更小的 y 位置至少 3 秒然后做一些事情。我假设有一个计时器,但不确定如何设置它。 Ta.

这需要 x 的自定义类型。 industry-grade 解决方案将使用模板而不是硬编码 double,但我在这里保持简单。

您的 class 看起来像这样:

class timedVariable {
   double value; // <double> would be replaced by template parameter
   std::chrono::steady_clock::timepoint lastChange;
public:
  timedVariable(double v) 
    : value(v)
    , lastChange(std::chrono::steady_clock::now())
  { }
  timedVariable(timedVariable const&) = default;
  timedVariable& operator=(timedVariable const&) = default;

  bool equalSince(double v, std::chrono::steady_clock::timepoint t)
  {
     // Ignoring the problem of double equality 
     return this->value == v && lastChange < t;
  }
};

"less than X for Y seconds" 的一个小问题是您需要相当完整的以前值的历史记录。例如,如果您过去在时间点 0、1 和 2 有值 0.1, 0.3, 0.2,而您在时刻 3 检查,那么它永远 <=0.3,但有一秒钟 <=0.2。你需要 "greater than X for Y seconds" 的逆向历史。

如果您可以预先限制历史记录的长度,那么问题就不大了。您可能知道您最多只需要 3 秒的历史记录,这意味着在分配新值时,您可以从丢弃过时的历史记录开始。