# Timed series of events. Logic for organizing events based on time?

I would like to execute a series of events at the time at which they occur.

The events are stored in a list and always sorted by time of execution.

``````volatileEvents.Sort(SortScriptEventAscending.Comparer);
``````

I would like to have my update method execute the following points.

• The list should be checked to see if it contains any events (if not then don't continue)
• The events should be executed and remain in the list until the next event is executed
• Once the current event is executed the previous event should be removed
• Events should always be checked to see if they have either expired or are yet to occur

I have the basic conditions implemented but the algorithm doesn't work as intended.

``````        float currentTime = game.ScriptTimer.CurrentTime;

int numEvents = volatileEvents.Count;

// Check for no events
if (numEvents == 0)
{
return;
}

// Check for expired events
while (volatileEvents[0].Time < currentTime)
{
volatileEvents.RemoveAt(0);
}

// Check if the current event has yet to occur
if (volatileEvents[0].Time > currentTime)
{
return;
}

// Protect against index range error
int next = numEvents == 1 ? 0 : 1;

ScriptEvent currentEvent = volatileEvents[0];
ScriptEvent nextEvent = volatileEvents[next];

// Update the current value based on the script and event parameters
float value = currentEvent.Interpolate ?
MathTools.Lerp2D(currentEvent.Value, nextEvent.Value, currentEvent.Time, currentTime, nextEvent.Time) :
currentEvent.Value;
``````

I would like some help to achieve the four bullet points as the basic conditions are there but the method's order of execution is incorrect.

-
Why does an event have to stay in the list while it's executing? And it really should stay there even after it's finished? –  svick Jun 6 '12 at 13:48
Good question. It needs to stay there because of the interpolation code (Lerp2D needs the value). I could store the value only instead of course. –  user1423893 Jun 6 '12 at 13:56
In response to the second question. It is being removed so the current event is always at the same index of the list. No need for searching the list for the event. –  user1423893 Jun 6 '12 at 13:58
Worked this out with pen and paper last night. Problem can be considered closed or solved. –  user1423893 Jun 7 '12 at 9:34
Could you share your solution with us and post it as an answer? If you don't want to do that, you can delete this question. –  svick Jun 7 '12 at 9:44

My simplified answer (without interpolation or looping):

``````        int numEvents = events.Count;

// Check if there are any events to execute
if (eventIndex == numEvents)
{
return;
}

// Check if the current event has yet to occur
if (events[eventIndex].Time > currentTime)
{
return;
}
else
{
// Update the property based on the current event
UpdateProperty(events[eventIndex].Value);

// Current event has been executed so increase the event index
eventIndex++;
}
``````
-