Python / Pygame Tutorial: Animations with sprites
HTML-код
- Опубликовано: 2 июн 2024
- A tutorial about how to use sprites to create an animation on a button press and also how to control the speed of the animation, all happening in the Python module Pygame.
Project files can be found here: github.com/clear-code-project...
Basic tutorial on sprites: • Python / Pygame Tutori...
Assets I used: opengameart.org/content/opp20...
Link to the image in the logo: pixelartmaker.com/art/7b0362cb...
Absolutely genius way to handle animation speed, short and efficient.
you_said_it == True
the way you handled animation speed is just the best in my opinion,i was struggling with that but thanks to you i got it
Hey, thank you so much for your video!
I have started to learn pygame a week ago and I am currently working on a game. This video helped me a lot and you explain everything in a very good way!
Thank you!
2:46
Here, you can make a for loop which can loop through the name like:
for i in range(1, 11):
path_name = "attack_"+str(i)+".png"
image = pygame.image.load(path_name)
self.sprites.append(image)
If you are working with a lot of images, this may help
You can use f strings:
for i in range(1, 11):
image = pygame.image.load(f"attack_{i}.png")
self.sprites.append(image)
If you are working on a lot of images, is convenient having a spritesheet.
You can also use a list comprehension as short hand for the for-loop.
self.sprites = [pygame.image.load(f"attack_{i + 1}.png") for i in range(10)]
@@theyoutubeaccount8499 or format mthod
for i in range(1, 11):
image = pygame.image.load("attack_{}.png".format(i))
self.sprites.append(image)
@@0rd3r you're absolutely right but people generally prefer f strings as f strings are usually more convinient--especially when you have to use a lot of formatting--since you can manually place the variables where you want them to be instead of using the respectively logic.
Finally, I found it, you are the best. Thank you sooooooo much.
This is the best pygame animation tutorial on RUclips.
Amazing video! Really useful descriptions of everything and a great explanation too. Thank you very much!
Videos keep getting better!
IDK why this video shows now for me after 2 years of uploading but this is great thing
He helped me
In this video, your code is easy to use so it will help me make my own game better. Thank you !😊
Like your programming stile! Keep it up!
TYSM! You have helped me with lots of problems in pygame!
The animation speed was my main convern, thanks!!!!!
This tutorial was really helpful, thank you so much :D
hey ! i'm french and i find that you explain very good. You speak slowly and your vocabulary is simple !
i don't understand why you don't continute videos.
i'm french too and i agree with that
Thanks for the tutorial, it helped me a lot.
Finally know how to make a proper animation!
I suggest one simple improvement to the code (got it from stackoverflow):
When you load all the images for the animation, you use one line of code for each images (in the Player class).
You could do this instead:
for filename in os.listdir(folder):
img = pygame.image.load(os.path.join(folder,filename))
if img is not None:
images.append(img)
The only thing you need to do is assing the directory of the folder with all the images in it.
It will automaticly store all those images in a list.
I think that this is a little more robust, because if you want to change the animation you don't need to change the code.
(keep in mind that the order of those images in that folder are important)
Thanks!
Wonderful stuff !!! Thank you so much for theses videos.
I hacked this one time using PowerPoint: by copying instances of a single image, then working with the “appear” animated effect and the time of appearance and disappearance, then setting object in front of each other corresponding with animation I would make things blip across the screen lol ... that was my little hack.
Now I’m trying to understand this lol it’s taking some time. I just started learning like a week ago. Thank you for your tutorial.
Thanks a lot. I have successfully created my own animation of Goku using your help.
thanks for the video, this was something i wanted to know how to do.
Sprite Groups! I needed this! Thank you!
very clever fix for the animation speed
This saved me!! Thanks, awesome video!
Bro your tutorial is so cool!!!
This is amazing, thank you :)
awesome man, very helpful!
You deserve million subs
Thank you man great video
Excellent tutorial 👍🏽
Very useful! Thank you so much!!!
Thank you so much for this useful information
The way you slowed down the animation, that was really cool, I am so glad I could find your channel
what a wonderful coding!
Thank you sooooooo much. You save my week
Is it necessary to use self. for variables that will not be accessed from outside a class? For example, in your Player class, you create a self.is_animating boolean attribute. Could you just use is_animating instead?
That's cool man. Idk why you only have 30 likes, keep going 😊
now he has 245
@@scoopydevy 254*
@@forgandorgan7552 right
Now, there's 370!
Now 431!
how to make the back ground of the frog transparent so that it can be anywhere like the beginning of the vid and how to just let it automatically do action after a particular time
Thank you ! this was awsome
that's clever using int() to space out the frames
It's beautiful to see how you explain, I don't understand English, even so it is perfectly understood.
It would be great if you made the videos explained in Spanish. That way it would be much easier to understand for the Spanish-speaking public.
And your audience would grow much more.
MUCHAS GRACIAS TU VIDEO ESTA GENIAL!!!
Damm .. I thank RUclips , I saw this video in my recommendations .. Tried Searching this stuff
Thanks for the video!
for slowing down , i implemented a counter , that will count back till 10 one by one on each frame, after that update the sprite , and update itself back to 10 , simplest method that i developed myself
Make more videos, you have no idea how much you are contributing to beginners
good job! Thank you!
It's amazing 👍
like in the code , you use screen.fill((0,0,0))
but i don't want to fill the screen black , i want the background image in my game to remain same while running the animation
Awsome tutorial
Hora... Haina hola
Amazing this is super cool I enjoyed following along with the programming, however, my simulation seems to overlap images and not clearing the previous image why could this be the case ?
you need to add a background to the entire game otherwise you can always see the previous drawn frames.
Instead of using an if statement, would it be better to use the modulo operator to keep the current_sprite number under the max index length?
yes but the if statment serves to not just limit the current sprite number but also serves to end the animation
Aren't 3d moves made following the same principle? Would be interesting if you made a video about it too
Bro can you tell me if I pressed w it should show one animation with one button one
that frog pixelart was cool where can i get more like this
Note that in this implementation the final frame will display for a shorter period of time than other frames for values of speed < 1.
It simply needs to change >= to >
You can use
(animation_insex + 0.15) % length
Like this it would be lossless
Hey, this video was really good. I kept searching till I could find something like this
lol 2 years later i see this comment lmao
Thank you very much
@@ClearCode I have a question. The website u got it from was the pictures in a sprite sheet or separate images.
also if I make my own sprit sheet how does it cycle through the different images if they are all in the same sheet.
@@ech0_exe243 you would basically have to cut out a specific part of that sprite sheet and store it on its own surface. There are lots of other pygame sprite sheet tutorials, most of them use that approach actually. But it is rather tedious, I'm afraid.
@@ClearCode alright thank you! Im just starting animating for my game.
we can use:
for i in range(1,10):
self.sprite.append(pygame.image.load(f"attack_{i}.png"))
instead of repeating the same line...btw video was very helpful
Nice!
im new to OOP, can you tell me why animate() is called on player.animate() and not like this: moving_sprites.animate()?
Thank you so much
Yes this is a good video but you have any idea how to move the sprites on WASD events?
Amateur here, hopefully you got this after a year, but wouldn’t it just be
while keyinput(or whatever pygame uses for this) == true:
Proceed through the animating process with all that code from the video of the for loop?
@@Acradus lol i did get this after a yer, thanks though
question, i'm making a character and it can move right and left , it can also jump but when i stand still it freezes on one image even though i have 4 sprites for standing still, but it's not going through them, how can i add your method so that when i don't press anything it goes through the 4 sprites of the (still) variable in my code? here is the code if you want to see:
import pygame
pygame.init()
Width = 1024
Height = 224
win = pygame.display.set_mode((Width, Height))
bg = pygame.image.load('bg.png')
pygame.display.set_caption("A game")
icon = pygame.image.load('icon.png')
pygame.display.set_icon(icon)
walkRight = [pygame.image.load('right 1.png'), pygame.image.load('right 2.png'), pygame.image.load('right 3.png'),
pygame.image.load('right 4.png'), pygame.image.load('right 5.png'), pygame.image.load('right 6.png'),
pygame.image.load('right 7.png'), pygame.image.load('right 8.png'), pygame.image.load('right 9.png'),
pygame.image.load('right 10.png'), pygame.image.load('right 11.png'), pygame.image.load('right 12.png')]
walkLeft = [pygame.image.load('left 1.png'), pygame.image.load('left 2.png'), pygame.image.load('left 3.png'),
pygame.image.load('left 4.png'), pygame.image.load('left 5.png'), pygame.image.load('left 6.png'),
pygame.image.load('left 7.png'), pygame.image.load('left 8.png'), pygame.image.load('left 9.png'),
pygame.image.load('left 10.png'), pygame.image.load('left 11.png'), pygame.image.load('left 12.png')]
still = [pygame.image.load('standing 1.png'), pygame.image.load('standing 2.png'), pygame.image.load('standing 3.png'),
pygame.image.load('standing 4.png')]
baseLeft = pygame.image.load('enemy base facing left.png')
baseRight = pygame.image.load('enemy base facing right.png')
clock = pygame.time.Clock()
class Player(object):
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
self.vel = 5
self.isJump = False
self.jumpCount = 10
self.left = False
self.right = False
self.walkCount = 0
def draw(self, win):
if self.walkCount + 1 >= 36:
self.walkCount = 0
if self.left:
win.blit(walkLeft[self.walkCount // 3], (self.x, self.y))
self.walkCount += 1
elif self.right:
win.blit(walkRight[self.walkCount // 3], (self.x, self.y))
self.walkCount += 1
else:
win.blit(still[self.walkCount // 3], (self.x, self.y))
def redraw_game_window(): # anything to change for drawing is here
win.blit(bg, (0, 0))
soldier.draw(win)
win.blit(baseRight, (924, 110))
win.blit(baseLeft, (72, 110))
pygame.display.update()
# main loop for game
soldier = Player(200, 110, 64, 80)
run = True
while run:
clock.tick(50)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and soldier.x > soldier.vel:
soldier.x -= soldier.vel
soldier.left = True
soldier.right = False
elif keys[pygame.K_RIGHT] and soldier.x < 1024 - soldier.width - soldier.vel:
soldier.x += soldier.vel
soldier.right = True
soldier.left = False
else:
soldier.right = False
soldier.left = False
soldier.walkCount = 0
if not (soldier.isJump):
if keys[pygame.K_SPACE]:
soldier.isJump = True
soldier.right = False
soldier.left = False
soldier.walkCount = 0
else:
if soldier.jumpCount >= -10:
neg = 1
if soldier.jumpCount < 0:
neg = -1
soldier.y -= (soldier.jumpCount ** 2) * 0.26 * neg # ** double
soldier.jumpCount -= 1
else:
soldier.isJump = False
soldier.jumpCount = 10
redraw_game_window()
pygame.quit()
Well, I never try to make standing animations, but I think you can try to make a for loop who goes from 0 to less than 4 (number of your animation sprites) to keep scrolling the animation while your character is not in moving
Great job, this helped me a lot for understanding basics of pygame but my pictures wont open, do you have any clue what could be problem?
Hey, do you have the pictures in the same folder as the script? Do you get an error message?
@@ClearCode No they arent and yes an error message pops up.
@@ClearCode no they arent in same folder and yes i see error message
@@veljavracarevic6626 that is probably the problem then. If that doesn't work, what's the error message?
@@ClearCode sorry for so many replies. I wrote so many since when I was checking they weren't popping up. Anyways thanks for advice it worked. Keep up good work.
NIIIIIIIIIIIIICEEE BRO
thaaaank you! Could you please make a tutorial on good practice for modularizing code in pygame? It would be insanely helpful and I haven't seen any tutorials on the subject. Your work is insanely good.
that comes next Wednesday actually :)
@@ClearCode
@@tiran315 It will come soon! sorry
This is really confusing for what I'm trying to do :/
I'm making a top down game that updates the sprite based on the button that's pressed at the current moment and this code conflicts with that.
Could you make a video with a tutorial that plays an animation on the sprite during an event, rather than changing the sprite itself?
Like a death event that plays an explosion on a spaceship, or a shooting event that shows a fire/explode animation that comes out of a weapon?
this doesn't conflict with any of that. use the concept to write the code yourself.
Please tell how to add animated gifs to pygame
thank you
Great video but now how would we move the x and y position of that?
just change the values for self.rect to whatever you need, this is not going to affect the animation
That's a cool tutorial, but is there a way to have some sprites going faster than others?
Like sprite 1 stays for 4 frames and sprite 2 stays for 7 frames
you have a list of sprites, just copy the one you want to have multiply times a few times. Bit of a hack but should work well :)
Can i get the link of your music you using in this video?
3:10
Can we instead do ?:
For x in range(11): self.sprites.append(pygame.image.load(f"attack_{x}.png"))
yes, should be fine
Just forgot something b4 the appends
If x != 0:
@@user-ng4bc3cv6g I should have said: Yes, that should work in theory :)
@@ClearCode :)
hello! i am having a problem with my code where its saying AttributeError: 'str' object has no attribute 'get_rect' do you maybe know how to fix this?
nvm i fixed it i was just using os instead of pygame.image.load
Cool!
I downloaded the code and run it in vscode, what happened is there's no animation on the sprite. Can anyone tell me how to fix this.
Hey another great tut:)
I downloaded some sheets and cutted them in single PNGs. They are 250x250 but the figure on it is only 70x70 so when i load in pygame and do get.rect() i always get the 250x250…
Coding with russ has a good tutorial on how to use spritesheets. It'll solve your problem
@@blankblank1273 ok thank you will check it out:)
How do I increase the size of the frogs? I tried using these codes below but it didnt seem to work.
"""
self.current_sprite = 0
self.image = self.sprites[self.current_sprite]
self.image = pygame.transform.scale(self.image(300,300))
self.rect = self.image.get_rect(topleft = (pos_x,pos_y))
"""
i have the same problem, did you managed to figure out what it was?
My frogs are a bit small. How could I make them bigger?
Ok. Yes. This was straight forward. Super helpful for my first time using class. HOW DO YOU ROTATE THE FROG TO LOOK DOWN WHEN YOU PREES K_s!?!?
This is niec and simple, maybe too simple as this is not going to scale to large numbers of animations and sprites. I was hoping for something beyond the basics of playing animation is a fixed linear time i.e. easing functions etc
I changed the Payer __init__ method a bit :
self.images = ['attack_1','attack_2','attack_3','attack_4','attack_5',
'attack_6','attack_7','attack_8','attack_9','attack_10']
self.sprites = [pygame.image.load(frog+'.png') for frog in self.images ]
self.attack_animation = False
self.current_sprite = 0
self.image = self.sprites[self.current_sprite]
self.rect = self.image.get_rect()
self.rect.topleft = [pos_x,pos_y]
Can u add the Seperate PNG's in the asset files please..
hey so sorry for forgetting, added the link to the description now (github.com/clear-code-projects/animation)
please make a video on aniamtion via. spritesheets
Where can I contact you?
I am a student who is making a game. I need to have an interview with an expert in the field and I think you are a good choice.
I also need a little help in the game I am making so in the interview I will be making some queries.
,Thankyou
For my ref : Every frame we change the sprite image.But we want to reduce the speed ie after 5 frames we want to change the image to the next animation image,hence we need to increment by 1/5 = 0.2 every frame.
Hi, ii used to aply :
current-image +=1
current_image%=number_of_pictures
So it could be more efficient
Move to 7:49 to see button press animation
But you are not able to make animation faster this way, cause you are losing sprites. If you set speed =2, you show just 1, 3, 5 , 7, 9 sprites (or 0,2 ,4 ,6 ,8)... ????
"Player" object has no attribute "image"
even though I don't understand much English, I was able to follow along, thank you for your teaching.
could teach how to move character + map the same in game as Zelda - A link to The past.?
Hey, glad you liked it. And a zelda style tutorial is in the works, but I have some other things planned first, so it's gonna take a week or two
Thanks, I will follow and wait.
hey can you make a tutorial on flipping the player based on their movements? what it means is that lets say I put
if key[pygame.K_a]:
hope you understand this cause I am having a hard time trying to explain this
I want this without filling background black
just change screen.fill(0,0,0) to any other rgb value and you can choose just about any color
@@ClearCode I know that but I don't want that. I have solved it Thx
what da frog doin
This absolutely abolishes the idea of an sprite sheet. The idea is to have all the animations in one file so that you dont have to load 10 files and then iterate through them.
Nope that doesnt work for me
10:17
Pygame and pycharm are the same thing
Right?
nope
Really too clear with a peace voice and background.
Por que aqui só tem comentários br? kkkk
Ta moscando jão?
The frog won't appear when i run the code. I put the frog folder with 10 images in VS. Here is my code: pastebin.com/h1wAnqpx
hey, I had a quick look:
on line 25 you have a typo (it should be self.is_animating instead of self.in_animating)
on line 32 the if statement needs to be indented
Didn't have time to test it myself, but I realised that I didn't upload the project files, will upload it in a bit; then you can test it yourself.
Solved the problem... #drawing had to be on the same line as "for event in pygame.event.get():". Thanks for the quick response anyway :)
@@telband5314 well spotted! Indentations can be so pesky....