Skip to content

Instantly share code, notes, and snippets.

@sthairno
Created April 3, 2023 06:33
Show Gist options
  • Save sthairno/852471a042151b8933d2dc95904a17bb to your computer and use it in GitHub Desktop.
Save sthairno/852471a042151b8933d2dc95904a17bb to your computer and use it in GitHub Desktop.
ディレイとリピート機能を簡単に実装できるやつ
# include <Siv3D.hpp> // OpenSiv3D v0.6.6
class Delay
{
public:
constexpr Delay(Duration duration) noexcept
: m_duration(duration.count())
{
assert(duration >= 0s);
}
bool update(bool in, double d = Scene::DeltaTime()) noexcept
{
if (in)
{
m_time += d;
}
else
{
m_time = 0.0;
}
return in && m_time >= m_duration;
}
private:
double m_duration;
double m_time = 0.0;
};
struct Repeat
{
public:
Repeat(Duration interval, Duration delay = 0s)
: m_interval(interval.count())
, m_delay(delay.count())
{
assert(interval > 0s);
assert(delay >= 0s);
}
bool update(bool in, double d = Scene::DeltaTime()) noexcept
{
if (not in)
{
m_first = true;
m_delayed = false;
return false;
}
bool out = false;
if (m_first)
{
out = true;
m_accumulation = 0.0;
m_first = false;
}
m_accumulation += d;
if (not m_delayed)
{
if (m_accumulation < m_delay)
{
return out;
}
out = true;
m_accumulation -= m_delay;
m_delayed = true;
}
double count = std::floor(m_accumulation / m_interval);
out |= count > 0.0;
m_accumulation -= count * m_interval;
return out;
}
private:
double m_interval;
double m_delay;
bool m_first = true;
bool m_delayed = false;
double m_accumulation = 0.0;
};
void Main()
{
Delay delay0(0s);
Delay delay1(1s);
Repeat repeat0(0.1s);
Repeat repeat1(0.1s, 0.5s);
Graphics::SetVSyncEnabled(false);
while (System::Update())
{
System::Sleep(1s / 30.0);
ClearPrint();
bool source = MouseL.pressed();
Print << U"Source:\t\t\t\t" << source;
Print << U"Delay(0s):\t\t\t" << delay0.update(source);
Print << U"Delay(1s):\t\t\t" << delay1.update(source);
Print << U"Repeat(0.1s):\t\t" << repeat0.update(source);
Print << U"Repeat(0.1s, 0.5s):\t" << repeat1.update(source);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment