A minor change that helps understanding is to give your variables appropriate names (though nothing wrong with CalculatePosition necessarily):
function TweenSize(start, finish, step)
for size = start, finish, step do
local pos = start > 0 and start - size or size - finish
scriptsParent.Size = UDim2.new(size, 0, size, 0)
scriptsParent.Position = UDim2.new(pos, 0, pos, 0)
end
end
Now it is easier to analyze the line local pos = start > 0 and start - size or size - finish. Why do you want different behaviour if you're starting at a size greater than 0? In the case of TweenSize(0, 1, 0.05), pos = size - finish, which starts with 0 - 1 = -1 and then continues to 1 - 1 = 0. This is why you see the behaviour you do. If pos = start - size, which would start off as 0 - 0 = 0, and then proceed to 0 - 1 = -1, which is no better. You might want to redesign that line, thinking about what you actually want to happen in the general case. (Ideally you shouldn't have to worry about whether start is > 0 or not.) I believe your "working code" is presently making it so that the Gui object sticks to the lower-right of the screen. If that's what you want, then local pos = 1 - size is all you need.
If you wanted to make your function more general you might want to split the idea of tweening the size and tweening the position. Currently you're trying to do both without any additional arguments. One possibility:
function lerp(start, goal, amount)
return start * (1 - amount) + goal * amount
end
function Tween(startSize, endSize, startPos, endPos, numSteps)
local size, pos
for amount = 0, 1, 1/numSteps do
if amount ~= 0 then wait() end
size = lerp(startSize, endSize, amount)
pos = lerp(startPos, endPos, amount)
scriptsParent.Size = UDim2.new(size, 0, size, 0)
scriptsParent.Position = UDim2.new(pos, 0, pos, 0)
end
end
This setup is not particularly flexible (though lerp is fine) because startSize and endSize are expected to be numbers rather than Vector2s or UDim2s -- the function is assuming that you will only want to tween along a specific diagonal! If that's all you want, that's alright; otherwise it isn't difficult to use more arguments or to change their type (if you do that you'll also need to update lerp to use that type). If you use UDim2s, you can use their lerp function instead of the custom one above.
Also, do note that when using a for loop, the final iteration may not occur depending on how you set it up and rounding errors. For example, if you do for i = 0, 1, 0.3 do print(i) end, you'd get 0, 0.3, 0.6, and 0.9 (but not 1). To solve this, you might want a bit of code that places scriptsParent's Size/Position at the target values after the for loop.
However, it should be much easier to use TweenSizeAndPosition to do what you'd like (without the for loops):
scriptsParent:TweenSizeAndPosition(
UDim2.new(1, 0, 1, 0),
UDim2.new(0, 0, 0, 0),
nil, nil,
20/15,
true)
wait(20/15)
1 comment
e-e