Play anymation loop on Button A

Hi! I am creating an animation with the following code

import "constants"
import "CoreLibs/animation"

local pd <const> = playdate
local gfx <const> = playdate.graphics

class('Book').extends(gfx.sprite)


menuPosition = 1

function Book:init(x,y) 
    local cursorImage = gfx.image.new("img/book.png")
    IMAGETABLE = gfx.imagetable.new("img/book")
    self:setImage(IMAGETABLE:getImage(1))
    self:setCenter(0,0)
    
    self.animation = gfx.animation.loop.new(150,IMAGETABLE,false)

    self:add()
end

function Book:update() 

    self:setImage(self.animation:image())

    if pd.buttonJustPressed(pd.kButtonA) then
       self.animation:play()
    end


end

And it works. It play the first time on load of the sprite. But I got Nil object when I press A.

What am I getting wrong?

thx!

Ok , I think I got it.
I cannot re-play the animation so I ended up doing this:

if pd.buttonJustPressed(pd.kButtonA) then
        self.animation = gfx.animation.loop.new(150,IMAGETABLE,false)
    end

Is this the correct approach?

Instead of creating a new animation, you can directly set the properties of your existing animation.

self.animation.frame = 1
1 Like