spritesheet idea

i’m using some sprite sheets in my little dungeon demo. i do them by copying from the sheet image into smaller individual images. as far as i know, that’s the thing to do in codea for now.

i know we’re all about 3d and shaders these days, but it would be nice to have an additional drawing operation like sprite that included the cropping values right in the command, esp if it could work with a blit right to the screen rather than making an explicit copy.

just an idea …

you can use mesh to use a sprite sheet, although i recall reading somewhere here that mesh is going to be deprecated in C4 (why ??):

this assumes you will have the same rectangular bounding box for each image in your sheet, if you want to handle packed sprite sheets you will need to include the data for each bounding box x,y,w, and h and figure out the values needed in setRectTex

SpriteSheet = class()

function SpriteSheet:init(i)
  self.mesh = mesh()
  self.mesh.texture = readImage(YOUR_SPRITE_SHEET)
  self.atlasCols = howManyColumns
  self.atlasRows = howManyRows
  self.frame = theStartingFrame
  self.totalFrames = howManyTotalFrames
  self.colUnit = 1 / self.atlasCols
  self.rowUnit = 1 / self.atlasRows
end

-- the draw loop, use this to loop through an animated sheet, or set
-- the frame directly if your sheet is static
function SpriteSheet:draw()
  self.mesh:draw()
  self.frame = self.frame + 1
  if self.frame >= self.totalFrames then
    self.frame = 1
  end
end

-- this grabs the subsection of the sprite sheet and renders it into the mesh rect
-- it assumes all frames in the sheet have the same size bounding box (monospaced)
function SpriteSheet:setRectTex()
  local col = self.frame % self.atlasCols
  local row = math.floor(self.frame / self.atlasCols)
  self.mesh:setRectTex(1,
    col * self.colUnit,
    (1 - self.rowUnit) - (self.rowUnit * row),
    self.colUnit,
    self.rowUnit
  )
end

-- this creates a rectangle for the mesh to render into the draw loop
-- use this to change position, height/width and rotation
function SpriteSheet:setRect(id, x, y, w, h, r)
  local id = id or 1
  r = (r / 360) * (math.pi*2)
  self.mesh:setRect(id, x, y, w, h, r)
end

@skar the functionality of mesh will still exist in Codea 4, but the specific mesh related APIs will be superseded by something better

interesting, @skar … i’ll have to figure that out, looks like it might do what i’m thinking. thanks!

@skar got it, thanks!

needed an addRect. can’t setRect a non-existing rect

@Simeon will this break compatibility with the old code sharing posts on the forums? They are a rich source of learning…

needed an addRect. can’t setRect a non-existing rect
@RonJeffries

ahh my bad, i addRect in another class that i use for holding a physics body and mesh together, maybe it’s better to put that into the init but maybe there was a reason i can’t remember now that i didn’t