RunService.Heartbeat and FPS Question

I am creating an animation using ImageRectOffset using the sample code from the Roblox documentation:

-- Place this in an ImageLabel/ImageButton with size 256x256
local imageLabel = script.Parent

-- The following image is 1024x1024 with 12 frames (256x256)
-- The frames play an animation of a man throwing a punch
imageLabel.Image = "rbxassetid://848623155"
imageLabel.ImageRectSize = Vector2.new(256, 256)

-- The order of the frames to be displayed (left-to-right, then top-to-bottom)
local frames = {
	Vector2.new(0, 0),
	Vector2.new(1, 0),
	Vector2.new(2, 0),
	Vector2.new(3, 0),
	Vector2.new(0, 1),
	Vector2.new(1, 1),
	Vector2.new(2, 1),
	Vector2.new(3, 1),
	Vector2.new(0, 2),
	Vector2.new(1, 2),
	Vector2.new(2, 2),
	Vector2.new(3, 2),
}

-- Animate the frames one at a time in a loop
while true do
	for _, frame in ipairs(frames) do
		imageLabel.ImageRectOffset = frame * imageLabel.ImageRectSize
		task.wait(0.1)
	end
end

Instead of using a while loop with wait, as in the code above, I would like to use RunService.Heartbeat to run the animation at a specific frame rate.

The question is how would I use RunService.Heartbeat so that my animation runs at 30 FPS?

1 Like

You could do something like this:

local RunService = game:GetService("RunService")
local imageLabel = script.Parent

imageLabel.Image = "rbxassetid://848623155"
imageLabel.ImageRectSize = Vector2.new(256, 256)

local frames = {
	Vector2.new(0, 0),
	Vector2.new(1, 0),
	Vector2.new(2, 0),
	Vector2.new(3, 0),
	Vector2.new(0, 1),
	Vector2.new(1, 1),
	Vector2.new(2, 1),
	Vector2.new(3, 1),
	Vector2.new(0, 2),
	Vector2.new(1, 2),
	Vector2.new(2, 2),
	Vector2.new(3, 2),
}

local frameRate = 30
local Interval = 1 / frameRate
local elapsed = 0
local currentFrame = 1

RunService.Heartbeat:Connect(function(deltaTime)
	elapsed = elapsed + deltaTime
	if elapsed >= Interval then
		elapsed = elapsed - Interval 
		imageLabel.ImageRectOffset = frames[currentFrame] * imageLabel.ImageRectSize
		currentFrame = currentFrame % #frames + 1
	end
end)
2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.