Help with playing sprite sheet animations for enemies

This is my first post so please tell me if anything is unclear also sorry about grammar.

So my issue is that I have this enemy that I want to make a 2d sprite sheet looping animation for. Seems simple enough, I have done it plenty of times, However I want to be able to stop and start the animation at any time from different parts of the script.

I have tried somethings but either I don’t have enough understanding or its not what I was looking for.

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);
}

– I want to be able to start and stop the code below from a difforent line of code
– This is just an example of my issue, so the code below is from roblox
– I also don’t want the for do loop to finish, I just want it to stop instantly
while true do
for i = 1, #frames do
imageLabel.ImageRectOffset = frames[i] * imageLabel.ImageRectSize
wait(.1)
end
end

If you need additional info please ask.
Thanks for the help :smile:

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

local condition = false

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 function playFrames()
	while true do
		for i = 1, #frames do
			if condition then
				imageLabel.ImageRectOffset = frames[i] * imageLabel.ImageRectSize
				task.wait(.1)
			else
				break
			end
		end
	end
end

local function stopFrames()
	condition = false
end

playFrames() --this will start looping through the sprite sheet's frames when called
stopFrames() --this will stop the spritesheet looping at the exact frame this is called

Should be relatively simple to understand what I’ve added.

1 Like

Thank you. This was a lot more simple then I thought it was going to be, but works just as well. :smile:

Wait It doesn’t work, you have to use coroutines. It’s not a hard fix though