Save player positions for 3 last seconds

I’m trying to recreate tracers rewind ability, where she can rewind her position for the last x seconds (using 3 for now)

right now, i’m using this code:

-- save data, written on phone so might be slightly off 
coroutine.wrap(function()
   while wait(0.05) do
       local count = 1 
       for i,v in Positions do
            if os.clock - v.Time > 3 then
                Positions={}
                break end 
                count+=1
            end
      end
       Positions[count] = {
["CameraCFrame"]=Camera.CFrame, ["Player Pos"]=Character. HumanoidRootPart.CFrame ["Time"]=os.clock()
}
     end
end)

-- use list

for i = #Pos, 1, -1 do
local index = Pos[i]
end


although this code leads to positions being wiped every 3 seconds (position = {}) and you can sometimes have a really short rewind.

what would be a better way to store players position for the last 3 seconds?

What you want to do is to only remove positions that were from more than 3 seconds ago without wiping all of them.

local Positions = {}

coroutine.wrap(function()
    while wait(0.05) do
        -- Save the latest position
        table.insert(Positions, {
            -- Put properties
        })

        -- Iterate backwards so that removing entries doesn't 
        -- shift the elements after it
        for i = #Positions, 1, -1 do
            if os.clock() - Positions[i].Time > 3 then
                table.remove(Positions, i)
            end
        end
    end
end)()

Because the table is updated every 0.05 second, there could be positions that are from up to 3.05 seconds ago. If that’s a problem, then you will have to either increase the update frequency or use a for loop and recheck the time whenever you want to use it. If not, then simply doing Positions[1] will give the oldest position within 3.05 seconds.

1 Like