Skip to content

Instantly share code, notes, and snippets.

@omikun
Last active July 27, 2017 00:46
Show Gist options
  • Save omikun/795b26d91116b0db36185e352035b27d to your computer and use it in GitHub Desktop.
Save omikun/795b26d91116b0db36185e352035b27d to your computer and use it in GitHub Desktop.
helper classes for managing times w/o an event scheduler
public class Timer {
public float StartTime;
public float Duration;
bool Idle;
public Timer(float d)
{
Idle = false;
Duration = d;
StartTime = Time.time;
}
public bool isReady()
{
return Time.time > StartTime + Duration;
}
//Start timer or reset Start Time
public void Reset()
{
StartTime = Time.time;
Idle = false;
}
public bool ResetIfReady()
{
if (Idle || isReady())
{
Reset();
return true;
} else
return false;
}
public void ResetIfIdle()
{
if (Idle) Reset();
}
public void SetIdle()
{
Idle = true;
}
}
// FSM supports basic timers
// a volley timer
// a finer unit timer that runs per volley
// a reload timer
public class WeaponFiringFSM {
public float ReloadRate = 2;
public float ReloadAmount = 1;
Timer ReloadTimer;
Timer VolleyTimer;
Timer UnitTimer;
public float VolleyInterval = 5;
public float MissileInterval = .2f;
int NumFired = 0;
public int NumPerVolley = 4;
public int ammo, startingAmmo = 5;
delegate void ActionDelegate();
ActionDelegate action;
public WeaponFiringFSM(Delegate a) {
Initialize();
action = a;
}
public void Initialize()
{
ammo = startingAmmo;
NumFired = 0;
ReloadTimer = new Timer(ReloadRate);
VolleyTimer = new Timer(VolleyInterval);
UnitTimer = new Timer(MissileInterval);
}
public Tick()
{
//check if ready to fire volley
if (VolleyTimer.isReady())
{
if (ammo > 0 && UnitTimer.ResetIfReady())
{
action();
NumFired++;
ReloadTimer.ResetIfIdle();
if (NumFired >= NumPerVolley)
{
VolleyTimer.Reset();
NumFired = 0;
}
}
}
//check if need to reload
//need to reset reload timer only either when time runs out or missile fired
//reloadTimer needs an idle state: isReady but
if (ammo < startingAmmo)
{
if (ReloadTimer.ResetIfReady())
{
ammo += ReloadAmount;
if (ammo >= startingAmmo)
{
ammo = startingAmmo;
ReloadTimer.SetIdle();
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment