-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPlayerReplay.cs
More file actions
76 lines (56 loc) · 1.8 KB
/
PlayerReplay.cs
File metadata and controls
76 lines (56 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
using System.Collections.Generic;
using UnityEngine;
public class playerReplay : MonoBehaviour
{
public Playermove player_script;
public struct InputFrame
{
public float time;
public float horizontal;
public bool jump;
}
[SerializeField] private float maxRecordSeconds = 10f;
private readonly List<InputFrame> frames = new List<InputFrame>(2048);
public IReadOnlyList<InputFrame> Frames => frames;
private bool jumpQueued;
public void QueueJump() => jumpQueued = true;
void Awake()
{
}
private void FixedUpdate()
{
// get what player did in this frame
frames.Add(new InputFrame
{
time = Time.time,
horizontal = Input.GetAxisRaw("Horizontal"),
jump = jumpQueued,
});
// jump happened, anything past max record seconds is shaved
jumpQueued = false;
float cutoff = Time.time - maxRecordSeconds;
int removeCount = 0;
while (removeCount < frames.Count && frames[removeCount].time < cutoff)
removeCount++;
if (removeCount > 0) frames.RemoveRange(0, removeCount);
}
// get player input from a certain time
public bool TryGetFrame(float targetTime, out InputFrame frame)
{
frame = default;
// if nothing happened, doesn't do anything
if (frames.Count == 0) return false;
// show the frames to the shadow in opposite order, find the most recent one
for (int i = frames.Count - 1; i >= 0; i--)
{
if (frames[i].time <= targetTime)
{
frame = frames[i];
return true;
}
}
// Can't go back that far, oldest frame is the first one
frame = frames[0];
return true;
}
}