Pygame Sprite Sheet Tutorial: How to Load, Parse, and Use Sprite Sheets
ฝัง
- เผยแพร่เมื่อ 5 ก.ย. 2024
- In this tutorial, we'll be learning all about sprite sheets. We'll discuss why we use them, and how you can start implementing them into your games immediately.
Code and images for this tutorial can be downloaded at: github.com/Chr...
Texture Packer: www.codeandweb...
Personal Channel - / @ur_homedawg
Pokemon Trainer sprites belong to Nintendo and were used for educational purposes. Sprites were ripped by Tsuka
#gamedev #Pygame #Python
I don't understand why this video only has 3k views. All of the "big" pygame sprite tuts were showing me how to load in each frame as a separate image, which was NOT the solution I or really anyone should be looking for. Thank you for this godsend of a tutorial
That's part of the reason I made this tutorial. I appreciate the kind words : )
This was so informative and I was fascinated when you used the json file for metadata and using (index + 1) % len(frames) instead of a loop. I hope to learn more from your videos!
JSON is just a text file/text format at the end of the day. It's not magic at all. You don't have to use JSON, you can use pretty much any format you want. Hell, you can even make up your own file format if you wish, as long as you know how to read the text into your program. He used a JSON library because many languages have built in JSON support, which makes it very easy to read JSON text files into your program.
Need to go to sleep but your videos are so good!
Appreciate the kind words!
Same 😂
Hey man just wanted to say thank you so much for this tutorial! I've always done sprite based games in java or c++, but have really fallen in love with python lately. you literally saved me a day of sifting through stack overflow! Subscribed.
Glad you found what you needed! Appreciate the support : )
These are great! I know some python from before and wanted to play around with pygame. I like how you do it using classes, feels more pythonesk then some other sources I've checked out.
Also you explain every step nice and clear. Keep it up. Gonna go through your whole series.
Thank you!
By far the best video I've seen for spritesheets (at least for pygame/python)
after many videos, this is one of the best for learning sprite sheets as a complete beginner, thank you.
Hey man I just finished my Cs project this video was a massive help and really boosted my confidence using json files and the concpet of spritesheets. Thank you sm !!!!
Right on, happy it helped : )
Hands down the best sprite sheet tutorial for pygame on TH-cam
Glad you found it helpful!
nice tutorials. keep it up!
Thank you! Look forward to more :)
very nice, one of my greatest doubts about how to load sprites in pygame.
tks for your great explanation!
SO HELPFUL, I didnt know how to use a sprite sheet and was trying to store each frame as its own file... it got wayyyyyy messy way fast
I really want to know this procedure, however, the video goes out of focus often, so I cannot see what it is you are doing, and your voice runs words together so that I cannot separate the words.
I wish I could get a focused and clear version of this video. It seems to be a very effective process. Thank you for posting it.
Hey there, I appreciate the feedback. I'll work on improving video quality and not slurring my words together. Making videos is still a work in progress for me. Here's a summarized version of the process I use:
1. Create a sprite sheet with a software of your choice (I use TexturePacker)
2. Create the SpriteSheet class : github.com/ChristianD37/TH-camTutorials/blob/master/spritesheet/spritesheet.py
- The get_sprite function Cuts an image from your spritesheet at the specified x-y coordinates
- The parse_sprite function reads in the metadata for your spritesheet (file that contains all the x-y coordinates for your images, ususally a .json) and uses the get_sprite function to cut it out and return it
3. Use the parse_sprite function in your game whenever you want to change call an image, using the image's name as the input.
I'd be happy to answer any questions you might have, thanks for taking the time to comment : )
@@CDcodes Thank you for the link. And for the response. I think the focus issue may be something TH-cam does. You can improve your vocal delivery I am sure. I live in the boonies with a satellite internet, which is often interrupted, so the technical difficulties are not necessarily your fault. I get uninterrupted videos from Packt, so I blame TH-cam for many things I look forward to your tutorials.
@@CDcodes Thanks again. I think I can figure out how to call a sprite sequence on my own with your method. I also want to call a sound file or midi file at the same time for the sprite call. Do you have a method for that?
I haven't had to use a specfic method for that but here's how I'd approach the problem (hopefully I understood it right):
In pygame you can create a sound object by using the Sound class, which will look something like my_sound = pygame.mixer.Sound("my_sound.wav"). This sound could then be played anytime you call the "play()" function ( ie. my_sound.play() ). If you need to play a sound at the time a sprite is called, maybe you could make a list or dictionary of sounds that corresponds with the animation loop? Then you'd able to iterate through it the same way and play it in the animation function.
So for example my characters has a 2 frame walk animation and each frame should have a different step sound. Then I could update the sprite like in the video and also include something like:
if time_passed is enough:
current_frame = next sprite in animation sequence (Using the algorithm)
image = walk_frames[current_frame] # load next image
sound_list[current_frame].play() # play the appropriate sound
You'll also want to pre-initialize the mixer, or else there will be a delay in your sounds. Include pygame.mixer.pre_init(44100, -16, 2, 2048) in your code.
Hopefully that helps. Or if you find a better way let me know :)
@@CDcodes Excellent answer! That is the approach I was hoping for. Thanks for the mixer pre-initializing tip. I can't wait to try it! Thank you very much!. I may have to take a different approach when the sound clip, such as a spoken word, takes longer than a frame of the sprite sheet, but for anything I can whittle down to the fps of the game, this may work. There are four categories of sounds I wish to sync with my sprite play: Midi sounds, recorded clips of voice or sound effects like Foley as your step sound example is, music in WAV or MP3, and I hope to figure out how to make the characters speak with synthesized voice which is created in-game with a mini engine, so the character can respond to player input. Not very ambitious, but then, I am just beginning. I appreciate the time and energy you have given to my questions!
Wow, this is really informative video! Thanks!
Your welcome!
This was the only thing bugging me, thanks for the trick
*subscribed*
Appreciate it!
great work sir.
you could have also used more elegant pygame subsurfaces , as they are easy to understand
it is also a oneliner , so it makes the job of extracting every single sprite from the spritesheet easy
anyways , thank you .
Haven't heard of those before, thanks for sharing
congrats on 10,000 dude
Thanks a ton : )
Literally amazing video!
Thank you!
this has been a great help, thanks for the vid. keep it up!
Glad it helped!
for the second problem, my reccomendation would probably be, just dont place anything above or to the left of the sprites you already have and you should be good :p
with: context managers automatically close the file on your behalf when the block exits, even if an exception occurs, so no need to explicitly close the file @ 9:41
You are correct
hi, im following this tutorial and ive made my own spreite sheet but i dont have a meta data, do you know if theres a tool i can use to get the x, yw, h, of one of the sprites?
Hiya! You can use texture packer like I showed at the beginning of the video (it can take an existing spritesheet and parse it). Someone else mentioned a different program in a previous comment that I havent tried, but it seemed to work for them. You can shop around on google and look for a program that suits your best budget/uility needs
I followed all of the code (up to before the json part), but when I tried with my sprites, it didn't render them, and I can't figure out why.
really helpful tutorial!
Thanks a lot sir ☺️
Happy to help!
Nice editing
ive just got a question about the .jsop file, how would you get or create that file if you made your own spritesheet? or is it just sort of like cropping out the individual sprites from the spritesheet? your tutorial was very easy to follow and vey educational, thanks very much.
You can use software (such as TexturePacker) to combine all the images and generate the json file for you. Someone else in the comments mentioned www.leshylabs.com/apps/sstool/ , which will create a mapping for you. Or you can make it yourself with something like aseprite by placing all the sprites on a single image and manually creating the .json file.
Christian Duenas thanks 🙏
Does it have to be a json file or can I use txt to parse through
Caleb Welsh it can be any file im pretty sure, you just need the coords. The leshy labs thing is really good, it makes a jsop or txt for u
@@timothyli3360 swear goodLs
Very intuitive system, unfortunately it doesn't cover over pivot points, so centering images using object (i.e screen / other surface) width and height is going to always leave them with an offset.
9:38 why do you use close()? you used with then no need to use close ().
You're right it was unnecessary on my part
MAIS WSH ARTICULE QUAND TU PARLES J'COMPRENDS UN MOT SUR DOUZE
Thanks dude u hlp me alot
Awwwwwwweeeeesssssooooommmeeeee🔥🔥🔥🔥🔥🔥
Hey man, it's working but one every 2 frames become invisible(transparent) can you help me?
What was that shortcut to get the cop and past to change the 1's to 2's and such, that sweet.
In pycharm you can use ctrl+alt+j+shift to highlight all instances of a word
3:18 in that line you should not write self.sprite_sheet = pygame.image.load(self.filename) as an argument actually instiead only 'filename'?
Hey! I'm very new to using spritesheets as i've just blit the images individually before, but now i've finally learnt how to use them. I just have the issue that now i can't resize the pictures with pygame.transform.scale() because it's in the form of a list. Can you tell me how to resize the sprites.
Actually i found a way to get it working. My problem was that i was doing this. current_sprite = trainer[index]
pygame.transform.scale(current_sprite, (636, 520))
and the game would of couse update the variable every frame, but it worked when i just did this:
current_sprite = pygame.transform.scale(trainer[index], (636, 520))
canvas.blit(current_sprite, (0, 0))
Great tutorial!
I keep getting a JSON decode error and I don't know what it means.
Unexpected UTF-8 BOM (decode using utf-8-sig): line 1 column 1 (char 0)
File "C:\Users\User-Pc\Dot\spritesheet.py", line 10, in __init__
self.data = json.load(f)
File "C:\Users\User-Pc\Dot\dot.py", line 121, in
my_spritesheet = Spritesheet('spritemap1.png')
There's something wrong in the spritesheet.py file and I dont know how to fix it. Any help?
I see. Might be the way yours json file is structured. Come to the discord and someone might be able to help you out!
When do you think it is important to use sprite sheets? For instance if one is making flappy bird, dont you think it will be better to just load the pngs?
Hey! There's never really a wrong time to use a sprite sheet, since it will be more efficient than loading the .pngs from a directory. But if you're working on a small project, the difference will most likely be negligible enough to where you don't need them. The important thing to remember is to apply the .convert() argument to your images. This will help with optimization.
I don't know if this has been asked, but here I go.
I'm new to pygame, so is there any way that I can get the loop to cycle through the sprites while I hold the space bar down, rather than having to mash it?
Any help is appreciated.
Sure. What you could is assign a variable that is true when space is held down, false if its released. Then run the animation if such. Something like
If space down:
Space_pressed = T
If space up:
Space_pressed = T
If Space_pressed
Play_animation()
Google Pygame.KEYDOWN for some examples
how do i slow down the INDEX change speed ?
how do you get the spritesheet json meta data? I used the microsoft meta data extractor, but it can't extract meta data for PNG
You can use software (such as TexturePacker) to combine all the images and generate the json file for you. Someone else in the comments mentioned www.leshylabs.com/apps/sstool/ , which will create a mapping for you. Or you can make it yourself with something like aseprite by placing all the sprites on a single image and manually creating the .json file.
I am stuck at a part. Can you please make a tutorial on how to convert images to .json? I have gone through several gits and stack overflows... But i seem to not be able to figure it out. Can you pls make a tutorial on how YOU made the spritesheet as .json? Other than that, great explaination!
Hey. I mentioned it a bit in the video but I used a software called TexturePacker to create the json file for me. You can download a trial at www.codeandweb.com/texturepacker, or pay 20 bucks for a license to use it.
Hey, amazing videos! Thanks a lot! I am trying to run the sprite on a loop in the background of the menu I made (by following your tutorial), I am not sure how to put it on a loop and exactly where that code need to go. I got it working for an image in the menu.py but to run it on a loop does it have to be in the game.py? I am confused, since menu inherits a lot from game. Any help would be much appreciated.
Again, thanks for these vids! Really good for getting up to speed with Python.
Thanks Daniel! I think what you're looking to do is like what I have in my devlog here: th-cam.com/video/snh2suwLBVI/w-d-xo.html
Here's how you can do it:
1) In your main_menu.init() function, load up all of your frames into a list
2) make a function in your Main_Menu class called "draw_sprite()"
3) In draw_sprite () use the time to keep track of which animation frame to display (check out my vid on animation) Once you have the frame, blit it onto your display at a specified (x,y).
5) Place the draw_sprite function in the "display_menu" function after you reset the screen
Hope that helps! Lmk if you have any other questions!
@@CDcodes Thanks so much for this! This is gonna keep me busy. I will look into those other vids too. TY
@@CDcodes Just another question, if you could maybe help me in the right direction? I am planning on building a ChooseYourOwnAdventure style game. So it would rely on full screen sprites as background illustrations with text on screen. From a structural perspective, would you write the pages into one python file? or would there be loads of python files for each page and a main game file that would call them?
Definitely different files. I have a template that may help you. I can send it in the morning : )
@@CDcodes That would be amazingly helpful! Thanks!
How do I scale
I'm not making a game I want to make a video using the sprite sheet. so like 1. would it be a problem? 2. would I have to idividualy cut them out sepately and green screen them? what would be proper size to keep a sprite in good view?
In theory its possible to create a video with a spritesheet. I think it would be easier to use a traditional animation software though, especially if you'd plan on putting every frame into a spritesheet
@@CDcodes I don't know about every frame but but say one specific motion. like say. prinny spinning around. or kirby running. but I understand.
@@CDcodes i" mainly looking to create an intro for my videos
@@AwestruckEarl In that case its definitely possible. I made my "Thanks for playing" outro in Pygame.
This might as well be a 14 minute ad for Texture Packer because holy shit, the free version does NOT do what we need it to do, and the leshy option doesn't seem to be any better, as when I use those coordinates it just doesn't display ANYTHING. Sucks to develop programs when you're poor
How would I parse an XML instead of a json?
Here's a helpful resource you could use: www.geeksforgeeks.org/xml-parsing-python/
@@CDcodes thank you. That helps a lot.
6:49 i'm getting the following error message
line 17, in
if event.type == pygame.QUIT():
TypeError: 'int' object is not callable
again, not sure what this is caused by and again, if i figure it out, i'll put it in here.
if like last time i find out that it's just me mistyping something or something other just like that, i'll just delete the comment, but until then, if you got a suggestion or a thought on what it could be, help would be appreciated.
for reference this is the part it's calling out the error in.
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT():
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
pass
It should be pygame.QUIT, not QUIT()
pygame.QUIT is just an integer key that refers to the X that closes a window. Adding the parenthesis makes the compiler think its a function.
Feel free to leave it up, other people might have the same problem : )
@@CDcodes nice one!
i actually found your channel while looking for a way to control the camera for a game i'm working on with my kids, i tried with your camera tutorial and was not sure how to implement it in the game we got so far, since our game is written in one script alone, it was hard to see how, where and when to get the camera script called in our game script.
do you have a discord server or something ? where i could share the game script with you in a DM ?
I don't have a discord server yet (maybe I should since this channel is starting to get some more attention) but for now you can email me.
@@CDcodes you definitely should try and get something like a server up, i could see your tutorials get good respons from other pygame users and i personlly believe the best thing for developers, professional or hobbyist, is to have a community where they can all share creations and feedback with each other.
i'm gonna wait with contacting you until the day you upload a video where you share your new server invite ;)
until then, gods speed and all the best to you.
Wait how did you create the meta data?
Its a software called texture packer, I mentioned it at the beginning of the video. Link is in the description. If you choose to use it, use the json3 output
@@CDcodes ty much much
this json method feels very unnecessary, it's a good tutorial but for a poor implementation that requires a paid program to be efficient... 90% of spritesheets are consistent grids that shouldn't require a json like this
How do you get the JSON File ?
You can use software (such as TexturePacker) to combine all the images and generate the json file for you. Someone else in the comments mentioned www.leshylabs.com/apps/sstool/ , which will create a mapping for you. Or you can make it yourself with something like aseprite by placing all the sprites on a single image and manually creating the .json file.
This is so cool hey dude can u help me with it to
Can you please go somewhat slow?
I'll keep that in mind, thanks for the feedback. In the meantime, you can set the youtube playback speed to a slower time if that helps!