script

 avatar
unknown
csharp
3 months ago
2.2 kB
15
Indexable
namespace StateRecord
{
    // class containing transform data in frame.
    public struct StateRecordFrame
    {
        public Vector3 pos;
        public Quaternion rot;
        public float timeStamp;
    }

    // class containing the recording info.
    public struct StateRecording
    {
        // recording name
        public string name;
        // the delay (in seconds) before next recording stamp
        public float recordDelay;
        // the list of frames
        public List<StateRecordFrame> frames;
    }

    // base class that records the pos/rot of this current transform.
    public class StateRecorder : MonoBehaviour
    {
        private bool _isRecording = false;
        private StateRecording _currentRecording;
        private float _currentTime;
        private float _lastTimeStamp;

        void FixedUpdate()
        {
            if (!_isRecording) return;

            if (_lastTimeStamp == 0 || _currentTime - _lastTimeStamp >= _currentRecording.recordDelay)
            {
                StateRecordFrame frame = CaptureFrame(_currentTime);
                _currentRecording.frames.Add(frame);
                _lastTimeStamp = _currentTime;
            }

            _currentTime += Time.fixedDeltaTime;
        }

        StateRecordFrame CaptureFrame(float timeStamp)
        {
            StateRecordFrame output = new()
            {
                pos = transform.position,
                rot = transform.rotation,
                timeStamp = timeStamp
            };

            return output;
        }

        public void StartRecording(StateRecording recording)
        {
            if (_isRecording)
            {
                Debug.LogWarning("Another recording is being processed, can't start a new one.", this);
                return;
            }

            _currentRecording = recording;
            _currentRecording.frames = new();

            _currentTime = 0;
            _lastTimeStamp = 0;
            _isRecording = true;
        }

        public StateRecording EndRecording()
        {
            _isRecording = false;
            return _currentRecording;
        }
    }
}
Editor is loading...
Leave a Comment