Rendering a brick between 2 points that will reach the point no matter the FPS

Basically no matter what FPS you get, the projectile/brick will reach the target at the same amount of time using CFrame:lerp. This is the method you should be using for things that use RenderStepped, instead of something like I did before:
speed * 1/60
each frame.

p1 is start position, p2 is end position, in this case p1 and p2 are actually bricks in the workspace.

local p1 = game.Workspace.p1.Position
local p2 = game.Workspace.p2.Position
local p = Instance.new("Part", game.Workspace) p.Anchored = true p.Name = "Brick"
local distance = (p1 - p2).magnitude -- distance
local speed = 50 -- speed
local itime = speed / distance
local totalpercentage = 0 -- The distance so far
print("Start",distance,speed,itime)
print("Should take ", distance/speed,"seconds")

wait(1)
local start = tick()
local stop = false
local event = game:GetService("RunService").RenderStepped:connect(function(alpha)
	if stop then
		return
	end
	local percentage = itime * alpha
	totalpercentage = totalpercentage + percentage
	if totalpercentage <= 1 then
		p.CFrame = CFrame.new(p1, p2):lerp(CFrame.new(p2), totalpercentage)
	else
		stop = true
		print("Time taken: ".. tick() - start)
	end
end)


while wait() do
	if stop then
		event:disconnect() -- Stop it from continuing to render
	end
end
1 Like

This is really… long.

Here’s what I use in one of my older games:

local Mod = {}

Mod.MovePart = function (Part, Target, Time)
local StartTime, Origin = tick(), Part.CFrame

repeat
	Part.CFrame = Origin:lerp(Target, (tick()-StartTime)/Time)
	game:GetService("RunService").RenderStepped:wait()
until StartTime+Time < tick() 

Part.CFrame = Target

end

return Mod

This runs in a module. It has no over-ride but it’s easy to read and will yield until finished.

Edit: Not sure how to tell the Edit box where code starts and finishes… because it never gets it right automatically.

Well the system I have, each projectile’s information is stored in a table, then a renderstepped loops through each one, updating it, and this system allows me to lower amount of rendering done.

I could do some benchmarks to see which is more efficient, but maybe another time.

Oh yeah. I have that for my animation editor/engine combo. It stores joints and their animation data in tables and loops through every frame.

I have a tweening module that stores all tweens in a table. Every RenderStep, it calculates all of the tweens with this:

local function CalculateTween(initial, target, start, duration, style, direction)
    local function styleFunc(n)
	    return TweenStyleFunctions[style](n)
    end

    local totalDelta = (target - initial)
    local elapsedTime = math.min((tick() - start), duration)
    local elapsedTimeProportion = (elapsedTime / duration)
    local deltaFactor = styleFunc(elapsedTimeProportion)
    local currentDelta = totalDelta * deltaFactor
    
    return (initial + currentDelta)
end