【问题标题】:How to create a "buffer" that stores previous value of a variable for each frame如何创建一个“缓冲区”来存储每个帧的变量的先前值
【发布时间】:2015-10-06 11:38:32
【问题描述】:

我需要知道 10 帧前变量的值。 我想过做一个数组,但是每帧偏移值似乎有点过头了。

有什么想法/想法吗?

【问题讨论】:

  • 如果您指定有关您的环境的更多详细信息,您可能会得到更好的答案。例如你用的是什么框架?
  • 我正在使用 Unity 和 C#,抱歉,忘记提及了。

标签: c# variables unity3d buffer


【解决方案1】:

您可以创建一个基于System.Collections.Generic.Queue<T> 的数据结构来存储每一帧的变量。

相对于Array 的优势在于您无需移动每一帧上的每个变量,只需添加最新的变量即可。这使它成为O(1) 操作,而不是O(n)

class History<T>
{
    Queue<T> data;
    public int MaxCapacity { get; private set; }

    public History(int maxCapacity) 
    {
        MaxCapacity = maxCapacity; 
        data = new Queue<T>(maxCapacity);
    }

    public void AddEntry(T newData)
    {
        if (data.Count >= MaxCapacity)
        {
            data.Dequeue();
        }
        data.Enqueue(newData);
    }

    public T Peek()
    {
        return data.Peek();
    }
}

用法

var h = new History<float>(10);

//on each frame
h.AddEntry(0.12345f);

//get the value 10 frames ago (or the earliest one recorded)
Console.WriteLine(h.Peek());

我将把它留给读者来实现更多的实用方法,例如Clear()

【讨论】:

  • 使用 MemoryStream 存储变量的值直到我需要它们是否有意义?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-27
  • 1970-01-01
  • 2023-03-07
  • 1970-01-01
  • 2011-01-11
  • 2020-01-11
相关资源
最近更新 更多