Is there a way to replace the draw method of sprite subclasses that are called by sprite.update?
Here's an example program. The behaviour I expect would be that it would print draw, however it does not. How do I modify the draw method used by sprite.update?
import "CoreLibs/sprites"
class("Example").extends(playdate.graphics.sprite)
function Example:init()
Example.super.init(self)
self:add()
end
function Example:draw()
print("test")
end
Example()
function playdate.update()
playdate.graphics.sprite.update()
end
You've defined a sprite class called Example, but you haven't instantiated any Example sprites. You'll need code somewhere that does
local myExampleSprite = Example()
This initializes a new instance of Example named myExampleSprite and adds it to the display list (because you call self:add() in Example:init() — maybe not the best place though).
You can just put this line at the bottom of the file and it will work for now, but eventually you'll need to write proper code for creating and configuring your sprites at the beginning of the game.
Also note that Example:draw() will only be called on sprites whose bounds are "dirty" (marked as needing redraw) unless you have called sprite.setAlwaysRedraw(true).
Oh my mistake — missed the Example() line. The problem is slightly different: you are instantiating a sprite, but it's not getting drawn because it has zero size, so there's no bounding rect to be redrawn, hence draw() is not called.
The fix is just to give your sprite a size after creating it:
local myExampleSprite = Example()
myExampleSprite:setSize(10, 10) // or anything nonzero
ahh okay that works for the example. it was the setSize combined with a parent class that did set an image in my game that was creating the issue. if an object has an image, it's draw method can't be overridden, correct?