Get Sprite by Name in a Sprite Sheet

Posted by dmekersa, Posted on January 27, 2012, Last updated January 31, 2012

1 vote

Are you upset with the order of you sprite sheets? I am :)

It's easy, for me, to sort sprite by name, example : "ship_1,ship_2", and to get the index of the first frame. Use the Basic layout in Zwoptex, then choose to order by name/Ascending.

Here is a short snippet to get a sprite picture index in a sprite sheet.

pSheetData is the sprite sheet used by sprite.newSpriteSheetFromData.
pName is the picture name, INCLUDING THE EXTENSION. Ex: "ship_1.png".

1
2
3
4
5
6
7
8
9
10
11
function getSpriteByName(pSheetData, pName)
        print("Log -- Enter - getSpriteByName "..tostring(pName))
        for k,v in pairs(pSheetData.frames) do
                if (v.name == pName) then
                        print("Log -- Exit - getSpriteByName return "..tostring(k))
                        return k
                end
        end
        print("Log -- Exit - getSpriteByName return -1 (not found)")
        return -1
end


Replies

krystian6
User offline. Last seen 25 min 38 sec ago. Offline
Joined: 6 Dec 2011

Thanks for sharing!

I think that you will need to work a bit on the performance side of things. Looping through all frames each time you want to create one sprite instance can become a bottleneck.