Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Sprite Animation

edited February 2017 in Code Sharing Posts: 15

I recommend passing in image() for readImage(...) for frames

SpriteAnimation = class()

function SpriteAnimation:init(frames, interval, repeat_, rewind, playing)
    self.frames = frames or {}
    -- converts any strings of image names into a codea image
    for key, img in pairs(self.frames) do
        if type(img) == "string" then
            self.frames[key] = readImage(img)
        end
    end
    -- frame interval at 10 by default
    self.frameInterval = interval or 10
    -- will not repeat by default
    self.repeat_ = repeat_ or false
    -- will start from the beginning after cycle default
    self.rewind = rewind or false
    -- does not start until instructed to by default
    self.playing = playing or false
    self.frameCounter = 0
    self.currentFrame = 1
    self.rewinding = false
end

-- this should be called every frame (in draw() function)
function SpriteAnimation:animate()
    if self.playing then
        self.frameCounter = self.frameCounter + 1
        if self.frameCounter == self.frameInterval then
            self.frameCounter = 0
            if self.rewinding then
                if self.currentFrame > 1 then
                    self.currentFrame = self.currentFrame - 1
                elseif self.repeat_ then
                    self.rewinding = false
                else
                    self.playing = false
                end
            else
                if self.currentFrame < #self.frames then
                    self.currentFrame = self.currentFrame + 1
                else
                    if self.rewind then
                        self.rewinding = true
                    elseif self.repeat_ then
                        self.currentFrame = 1
                    else
                        self.playing = false
                    end
                end
            end
        end
    end
end

-- returns current frame
function SpriteAnimation:frame()
    return self.frames[self.currentFrame]
end

-- resets animation
function SpriteAnimation:replay()
    self.playing = true
    self.currentFrame = 1
    self.frameCounter = 0
end

Comments

Sign In or Register to comment.