I am creating a game in Unity 3D and I have recently come up with my own simple replay system. It works well except for one small problem: it doesn't always start off where I would prefer it to in the recording of the gameplay. Basically every replay should be 8 seconds long. All I am doing for my replay system is storing the position and rotation of all objects in the scene, since there are only a few, in an array and then playing them back once an even is triggered.
I have the logical idea of how I should pick a starting point for the replay to start playing. I have a counter that increments every time my StorePosition() function is called in FixedUpdate(). That counter essentially gives me the number of indexes in the array so I know how many positions have been stored in total. All I should have to do is take that number and subtract from it the number of iterations that would occur during the 8 second replay.
My issue is that if I do the math for this: FixedUpdate() is called every .02 seconds which equates to 50 calls per second which would mean FixedUpdate() should be called 400 times over the time of my replay. So should I just be taking that total length of the stored positions array and subtracting that 400 and that would be the starting position in the array to start my replay?
That is the way I work it out in my head but it doesn't seem to work out quite right in the game. My counter seems to get into the 4000s or more over the 8 second replay so just subtracting the 400 from it doesn't give me anywhere near the amount of the replay that I want to see.
Is my logic flawed here? Any ideas?
2/21/2016
Here is some code for an example of how I handle this:
static Dictionary<GameObject, Vector3[]> positions = new Dictionary<GameObject, Vector3[]>();
public static int positionFillLength = 0;
static int index = 0;
public void StorePositions(GameObject[] objects)
{
foreach (var obj in objects)
{
if (obj != null)
{
if (!positions.ContainsKey(obj))
positions.Add(car, new Vector3[10800]);
positions[car][index] = car.transform.position;
positionFillLength++;
index++;
}
}
}
public void PlayReplay(int index, GameObject[] gobjects)
{
foreach (var obj in positions)
{
if (Array.IndexOf(gobjects, obj.Key) > -1)
{
if (positions[obj.Key][index] != Vector3.zero)
{
gobjects[Array.IndexOf(gobjects, obj.Key)].transform.position = positions[obj.Key][index];
}
}
}
}
So if I am storing values I just call StorePositions() at ever call of FixedUpdate() and send in the objects to get the positions of.
When it is time to play a replay, I just start calling PlayReplay(). I create an index that starts at size 0 and increments every time that PlayReplay is called, which will also be every time FixedUpdate() is called, and pass that along with the objects into PlayReplay().
index
is defined inStorePositions
or whatpositionFillLength
is used for. \$\endgroup\$