I’ve noticed from looking through the DevForum that there isn’t a lot of information on spritesheet iteration. There are some which use ImageOffset, however this isn’t great if your UIs are based off scale. A while ago, I was interested in iterating through spritesheets for generating GIFs and I managed to create some iterator code which can do this based off 4 variables: the image
, time (in seconds) per frame
, the number of columns
and the total amount of frames
.
Getting the assets/information
The first step is to get a spritesheet and upload it to Roblox (as a decal). If you do not have a spritesheet but you have a GIF, then you can turn the GIF into a spritesheet. I personally use the following website for this, although there are probably better ways:
GIF to Spritesheet Website Link
This website also provides video into GIF and a bunch of other features. Looking at the spritesheet, you should be able to get the number of columns and number of frames.
In the above image, there are 5 columns and 20 frames (5 * 4
).
You can get the timePerFrame
from the GIF, although if your timePerFrame is lower than 1/30, then it may not be exactly the same in terms of speed (although it won’t be noticeable!)
Iterator
The iterator works by setting the image size so that each frame in the spritesheet has a size of {1,0}{1,0}
which would mean that each frame would fit the UI perfectly.
Then, the code simply iterates through and sets the position every timePerFrame
so that each frame in the spritesheet is shown in the UI.
local imageLabel
local GIFs = {
['Example'] = {
timePerFrame = .1;
image = 'http://www.roblox.com/asset/?id=3671846574';
columns = 5;
frames = 20;
};
}
local currentGIF
local function calculateRows(GIF_Data)
return math.ceil(GIF_Data.frames/GIF_Data.columns)
end
local function calculateFrames(rows,columns,finalPanel)
local frames = {}
for row = 0,rows-1 do
for column = 0,columns-1 do
frames[#frames + 1] = UDim2.new(-column,0,-row,0)
if #frames == finalPanel then break end
end
end
return frames
end
local function loadGIF(name)
local GIF_Data = GIFs[name]
if GIF_Data then
local a = calculateRows(GIF_Data)
imageLabel.Image = GIF_Data.image
imageLabel.Size = UDim2.new(GIF_Data.columns,0,a,0)
currentGIF = name
local i = 0
local frames = calculateFrames(a,GIF_Data.columns,GIF_Data.frames)
spawn(function()
while currentGIF == name do
i = (i % GIF_Data.frames) + 1
imageLabel.Position = frames[i]
wait(GIF_Data.timePerFrame)
end
end)
end
end
loadGIF('Example')
--[[ Iterate through all the GIFs
for name,data in pairs(GIFs) do
loadGIF(name)
wait(10)
end
--]]
Roblox Spritesheet Example Place (LocalScript in ReplicatedFirst!)
spritesheet_example.rbxl (18.2 KB)