Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do I make this more accurate?

function tween(part,pos,tim,stop) --stuff
	local function stuff() --for the stopige
		local runs = 100 --smoooth
		local ToTake = runs*.03 --time it will take
		if ToTake>tim then
			repeat
				runs=runs-1
				ToTake = runs*.03
			until ToTake<tim --gets closer to tim
		else
			repeat
				runs=runs+1
				ToTake = runs*.03
			until ToTake>tim
		end
		local cf = part.CFrame --start cf
		for q=runs,0,-1 do
			wait()
			part.CFrame = pos:lerp(cf,q/runs)
		end
	end
	if stop then --stop! In the name of lo-o-o-ove
		stuff()
	else spawn(stuff)
	end
end

return tween

The above is a moduleScript. The purpose of it is to smoooooothly move parts. It works fine, but if I do something like this.

p1 = game.Workspace:WaitForChild("Part")
p2 = game.Workspace:WaitForChild("Part2")
tween = require(game.ReplicatedStorage.tweens)

start = tick()
tween(p1,p2.CFrame,10,true) --it has to pause here
print(tick()-start) --print 11.3

So, does anybody know how I could improve the accuracy of the time?

1 answer

✓ Accepted answer

You have the right idea with the lerp function. The goal here is to get a value between 0 and 1 and have it correlate to the time it should take for the entire tween to complete.

In my opinion the easiest way to do this is to get the tick when the tween is started and then find the difference in time after you wait or do a renderstep, etc.

So for example:

function tween(part, goal, finalt)
	local origin = part.CFrame; -- where we start from
	local start = tick(); -- the initial tick we compare to
	local dt = 0; -- the change in time from initial tick until now
	while dt < finalt do
		dt = tick() - start; -- update out time change
		part.CFrame = origin:lerp(goal, dt/finalt); -- get as percentage
		wait(); -- or renderstepped, etc...
	end;
	part.CFrame = goal; -- set it at the end to be precise
end;

-- example
local s = tick();
tween(game.Workspace.Part, CFrame.new(), 3);
print(tick() - s);

2 comments

2

Oh, thank you. I never thought about using tick() in a function before. Also, why the semi colons?

3

Habit from other programming languages

This discussion is preserved as it was. New answers, comments, and votes are closed.