I wanted to make a more optimized system for moving zombies in my td game but i don’t know how to lerp at a constant rate.
local CurrentCF = EnemiesTable[i].CF
local StartCF = Path.CFrame*CFrame.new(0, 1, Path.Size.Z/2-1)
local EndCF = Path.CFrame*CFrame.new(0, 1, Path.Size.Z/-2+1)
if math.round(CurrentCF.X) == math.round(EndCF.X) and
math.round(CurrentCF.Z) == math.round(EndCF.Z)
then
EnemiesData[i].Waypoint += 1
end
local ZombieMag = (EndCF.Position - CurrentCF.Position).Magnitude/TrackMag
local duration = ZombieMag / EnemiesData[i].Speed
local target = CFrame.new(CurrentCF:Lerp(EndCF, duration).Position) * CFrame.fromEulerAnglesXYZ(EndCF:ToOrientation())
You need to lerp the start CFrame and the end CFrame without changing the start CFrame. The reason that lerp isn’t constant is because the start is changing whenever the zombie moves. You could try something like this to fix the problem:
local target = CFrame.new(StartCF:Lerp(EndCF, duration).Position) * CFrame.fromEulerAnglesXYZ(EndCF:ToOrientation())
I got it to work with extra stored start time variable
local StartTime = EnemiesTable[i].StartTime
local CurrentCF :CFrame = EnemiesTable[i].CF
local StartCF :CFrame = Path.CFrame*CFrame.new(0, 1, Path.Size.Z/2-Path.Size.X/2)
local EndCF :CFrame = Path.CFrame*CFrame.new(0, 1, Path.Size.Z/-2+Path.Size.X/2)
if EnemiesTable[i].StartTime == nil then
EnemiesTable[i].StartTime = os.clock()
StartTime = EnemiesTable[i].StartTime
end
local Time = (EndCF.Position - StartCF.Position).Magnitude / EnemiesData[i].Speed
local alpha = (os.clock() - StartTime) / Time
local CAlpha = math.min(alpha, 1)
local target = CFrame.new(StartCF.Position:Lerp(EndCF.Position, CAlpha)) * CFrame.fromEulerAnglesXYZ(EndCF:ToOrientation())
if alpha > 0.95 then EnemiesData[i].Waypoint += 1 EnemiesTable[i].StartTime = nil end
EnemiesTable[i].CF = target