Beginner question: how to display N enemies of the same sprite without loading the sprite N times?

Hi there,

I realise this is a basic question but I'm recently getting back into coding, my only experience with LUA is toying around with Pico-8 long ago, and having to add() sprites to a list is sort of throwing me off a bit.

Say I wanna create an array of enemies, 10 of them, and they all use the same graphics, how do I go about making sure that the imageTable would be loaded only once but references by all the enemies in the array, instead of loading and taking up 10 times the amount of memory?

Bonus question: is there a way to bypass the add()/remove() system and display sprite arbitrarily?
Thanks!

You can load in the imagetable once and then pass it to every new sprite you create by accepting it as a param to its init function.

In the sprite class:

import "CoreLibs/object"
import "CoreLibs/graphics"
import "CoreLibs/sprites"

local gfx <const> = playdate.graphics

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

function MySprite:init(imagetable)
    MySprite.super.init(self)

    -- store a reference to the imagetable
    self.imagetable = imagetable

   -- other initialization…
end

To create your sprites:

local myImagetable = gfx.imagetable.new("images/mysprite")
local mySprite1 = MySprite(myImagetable)
local mySprite2 = MySprite(myImagetable)
-- ...

If you don't need the flexibility of passing different values in, I think you could also store the imagetable in a local variable defined in the same file as your sprite class (but not inside the class itself), and then just reference that from your sprite functions. I haven't tried that.

You might also find this useful:

1 Like

Very cool thank you!

1 Like