I'm trying to make an animation in which an image simultaneously moves downwards and disappears, like this:
However, I can't seem to get this to work properly. I only want the part of the screen with the animation to change, so I did something like this...
orect = pygame.Rect(oSprite.rect)
for i in range(10):
screen.fill(Color(255,255,255),rect=orect)
oSprite.rect.top += 12
print(orect)
print(screen.blit(oSprite.image, oSprite.rect, orect))
pygame.display.update(orect)
timer.tick(30)
where oSprite
is the Sprite representing the image I want to animate.
In the docs, screen.blit(source, dest, area)
should return a Rect representing the pixels that changed, but when I run my code, I get this (10 times over):
<rect(336, 48, 76, 74)>
<rect(336, 60, 0, 0)>
The second line is what was returned by screen.blit()
, meaning that it changed a 0x0 area, and indeed, all I see onscreen when the code is running is a sudden cut to white, rather than any animation at all. Why might this occur? As seen from the first print() statement, the rect that I entered for the area value was 76x74, not 0x0.
You need to blit on top of the oSprite.image surface, not the screen's surface.
This will draw another image on top of oSprite.image without extending on the screen if it is bigger.
oSprite.image.blit(new_image, (0,0))
Edited: Take this exmple, run it and see what is happening:
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((500,500))
run = True
#Animation Speed
speed = 0.1
#Load an image.
player = pygame.image.load("player.png").convert_alpha()
x,y = (0,0)
#Create a rectangular area to blit the player inside.
surf = pygame.Surface((player.get_width(),player.get_height()))
def Animate():
global y
if y > player.get_width():
y = 0
else:
y += speed
while run:
for event in pygame.event.get():
if event.type==QUIT:
run=False
break;
#Clear the surface where you draw the animation.
surf.fill((255,255,255))
#Draw the image inside the surface.
surf.blit(player, (x,y))
#Draw that surface on the screen.
screen.blit(surf, (20,20))
#Animate the image.
Animate()
pygame.display.update()
pygame.quit()
pygame.quit()
Imagine that surf is a piece of paper and you draw inside it the image and then you put that piece of paper on the screen.