Simple Sprite Sheet Example

Greetings! I have created a simple sprite sheet example that anyone can implement for their projects. In the example below, I am using the Tiny Dungeon sprite sheet by Kenney.

-- SpriteSheet

-- Use this function to perform your initial setup
function setup()
    -- Set display to fullscreen with overlay hidden
    viewer.mode = FULLSCREEN
    
    -- Optional: Disable antialiasing for pixel art
    noSmooth()
    
    -- Load sprite sheet named "tilemap.png"
    spriteSheet = readImage(asset.tilemap)
    
    --[[
    Create a copy of a sprite from the sprite sheet.
    In the example below, I am making a copy of a bat
    from the sprite sheet. The bat is on the bottom left
    corner of the sprite sheet, and it is 16 x 16 pixels.
    The pixels on the sprite sheet start from the bottom left
    which is on coordinate (1,1). To load the next sprite
    to the right, you would use (17,1). To load the sprite
    above the bottom left sprite, you would use (1,17).
    The sprites on the sprite sheet can be of any pixel
    size, as long as you start with the coordinate of the
    bottom left pixel of the sprite, and then specify the
    width and height of the sprite.
    ]]--
    --                           x,y,w, h
    spriteBat = spriteSheet:copy(1,1,16,16)
    spriteGhost = spriteSheet:copy(17,1,16,16)
    spriteSpider = spriteSheet:copy(33,1,16,16)
end

--[[
Draw the sprite in the middle of the screen.
WIDTH and HEIGHT automatically calculates the
width and height of the screen.
If you want to enlarge the sprite, specify the
width and height you want to scale the sprite to.
]]--
function draw()
    sprite(spriteBat, WIDTH / 2, HEIGHT / 2, 64, 64)
end
1 Like

And here’s what I use; hope it helps someone.

function createSprites(img, width, height, frames)
    self.spriteSheet = readImage(img)
    self.sprites = {}
    for i = 0, frames - 1 do
        local newSprite = self.spriteSheet:copy(width * i, 0, width, height)
        table.insert(self.sprites, newSprite)
    end
    return self.sprites;
end
-- this function returns a table with all the sprites in the sprite sheet, starting from index 1