Pygame: How Do I Make My Image Fall?
I am trying to make objects fall like they would on earth. I already got them to blit where I wanted them to but I can't seem to animate them. This is the object that I want to fal
Solution 1:
Give your class a self.speed_y
attribute and add the GRAVITY
to it each frame to accelerate the object. I've also added a self.pos_y
attribute because pygame.Rect
s can't have floating point numbers as their coordinates. So,
- increase the speed
- add the speed to the position (
self.pos_y
) - assign the
self.pos_y
toself.rect.y
.
Since you are already using a class, I recommend to make it a pygame sprite subclass (inherit from pygame.sprite.Sprite
). Then you can add all circles to a pygame.sprite.Group
and update and draw them by calling sprite_group.update()
and sprite_grop.draw(screen)
.
import pygame
GRAVITY = .2# Pretty low gravity.classCircle(pygame.sprite.Sprite):
def__init__(self, pos, screen):
super().__init__()
self.screen = screen
self.image = pygame.Surface((80, 80), pygame.SRCALPHA)
pygame.draw.circle(self.image, (30, 90, 150), (40, 40), 40)
self.rect = self.image.get_rect(center=pos)
self.pos_y = pos[1]
self.speed_y = 0defupdate(self):
self.speed_y += GRAVITY
self.pos_y += self.speed_y
self.rect.y = self.pos_y
if self.pos_y > self.screen.get_height():
self.kill() # Remove off-screen circles.defrun_game():
pygame.init()
screen = pygame.display.set_mode((1270, 670))
clock = pygame.time.Clock()
running = True
circles = pygame.sprite.Group(Circle((600, 0), screen))
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
returnelif event.type == pygame.MOUSEBUTTONDOWN:
circles.add(Circle(event.pos, screen))
circles.update()
screen.fill((10, 10, 30))
circles.draw(screen)
pygame.display.flip()
clock.tick(60)
run_game()
pygame.quit()
Post a Comment for "Pygame: How Do I Make My Image Fall?"