Skip to content

Instantly share code, notes, and snippets.

@Donnotron666
Created December 10, 2017 04:23
Show Gist options
  • Save Donnotron666/58fe76177e1391b2b1d3bc50fe28626f to your computer and use it in GitHub Desktop.
Save Donnotron666/58fe76177e1391b2b1d3bc50fe28626f to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
namespace Client.Game.Abilities.Utils
{
public class ActionSequence : List<ActionElement>
{
public float accum = 0f;
public int index = -1;
public float TotalTime {
get {
var ret = 0f;
foreach (var element in this)
ret += element.Duration;
return ret;
}
}
public void Insert(ActionElement element)
{
element.Timestamp = TotalTime;
this.Add(element);
}
public void Insert(Action action, float duration = 0f)
{
Insert(new ActionElement(action, duration));
}
internal void InsertContinuous(Action action, float duration)
{
Insert(new ActionElement(action, duration, true));
}
private int IndexAtTime(float time)
{
int i = 0;
var iat = i;
for(; i<this.Count; i++)
{
if (this[i].Timestamp <= time)
iat = i;
else
return iat;
}
return iat;
}
internal void InsertWait(float time)
{
Insert(() => { }, time);
}
public void Update(float dt)
{
accum += dt;
var newIndex = IndexAtTime(accum);
for( var i = index; i<= newIndex; i++)
{
if(i > index)
{
index = i;
//Debug.Log("Invoking action index " + i + " at time: " + accum);
this[i].Action();
return;
}
}
var current = this[newIndex];
if(current.Continuous)
{
current.Action();
}
}
public void Log()
{
var str = new StringBuilder();
foreach( var action in this)
{
str.AppendFormat("{0}:{1}\n", action.Timestamp, action.Action);
}
Debug.Log(str.ToString());
}
}
public class ActionElement
{
public float Duration;
public Action Action;
public bool Continuous;
public float Timestamp;
public ActionElement(Action action, float duration, bool callContinuously = false)
{
this.Duration = duration;
this.Action = action;
this.Continuous = callContinuously;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment