Log In  


You can use your spritesheets as-is in Picotron! First, add your spritesheet(s) into sprites in Picotron, like this:

Next, paste this function into your lua code (you can delete the comments for a smaller footprint):

-- spr_from_atlas() - draw to the screen a slice of a sprite atlas
-- param: s - sprite atlas to use (the number in the Picotron spritesheet)
-- param: idx - the 0-based index to render from the atlas
-- param: cols - number of columns in the sprite atlas
-- param: rows - number of rows in the sprite atlas
-- param: x - screen x-coordinate to draw top-left corner of the sprite
-- param: y - screen y-coordinate to draw top-left corner of the sprite
-- param: flip_x (optional) - flip the sprite horiztonally
-- param: flip_y (optional) - flip the sprite vertically
function spr_from_atlas(s, idx, cols, rows, x, y, flip_x, flip_y)
    -- assign default values to optional parameters if nil
    local fx = flip_x ~= nil and flip_x or false
    local fy = flip_y ~= nil and flip_y or false

    -- retrieve userdata about the sprite
    local spr_data = get_spr(s)
    local spr_w = spr_data:width()
    local spr_h = spr_data:height()

    -- calculate width and height of each atlas entry
    local w, h = (spr_w \ cols), (spr_h \ rows)

    -- determine where in the sprite's coordinate system to start referencing
    local spr_x = (idx % cols) * w
    local spr_y = (idx \ cols) * h

    -- sspr( sprite, sx, sy, sw, sh, dx, dy, dw, dh, flip_x, flip_y )
    sspr(s, spr_x, spr_y, w, h, x, y, w, h, fx, fy)
end

Note that the idx paramter counts from left-to-right, then top-to-bottom. With the example above, the first row of indices would count "0, 1, 2, 3".

Finally, just call the function when needed, and enjoy seeing your atlas come to life! Cheers!

12


1

Thanks for figuring this out! Very useful!


The guide was great. Simple access! scratch games


1

Hey thanks for making this, it's so useful! I'm trying to combine this function with your sprite rotation function (also super good), for use in sprite stacking. Do you think there is there a way to make this function return the userdata of a sprite in an atlas?

Update: I made a table in code to store the user data of each layer, so problem solved


1

Thank you,this is very useful! I love working with a texture atlas, it's way easier to keep an overview


Found a bug when using this myself - just updated the original post with the fix :)



[Please log in to post a comment]