0
\$\begingroup\$

I want the object to move continuously downward even while I'm pressing the upward key in keyboard. Eventually causing the object to drop completely after some moment.

character = pygame.image.load('pngfile')
character_size = character.get_rect().size

to_x = 0
to_y = 0

clock = pygame.time.Clock()

character_speed = 0.05

velocity_y = 0.1

#eventloop
running = True
while running:
        dt = clock.tick(60)
        for event in pygame.event.get():
                if event.type == pygame.QUIT:
                        running = False
                character.move_ip(0, velocity_y * dt)

so on and so on. I skipped the unnecessary parts to keep it short. Whenever I type the last line, move_ip doesn't become a method. It works find when I changed the object to pygame.Rect() but I don't know why this one isn't working. I got the keyboard control right but I just couldn't make the object to move constantly. Any help will be greatly appreciated.

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

because character is a pygame.Surface, not a pygame.Rect, so it can't be moved: AttributeError: 'pygame.Surface' object has no attribute 'move_ip'

the Rect and Surface are two are different but related objects: the Rect describes the position and size of the thing we want to draw, and the Surface describes the image that we want to draw.

In your example code, character_size isn't a Rect either, just a two-tuple containing (width, height). That is the size we want, but it needs to be applied to a Rect first.

Once you have a Rect of the proper size, then you can update its position with Rect.move_ip.

Finally, you can draw character using this rect.

screen = pygame.display.set_mode((240,180))
character = pygame.image.load('test.png')

# note - I am copying the entire rect rather than just
# its size so that I have something to move.
character_rect = character.get_rect().copy()

clock = pygame.time.Clock()
velocity_y = 0.1

running = True
while running:
        dt = clock.tick(60)
        for event in pygame.event.get():
                if event.type == pygame.QUIT:
                        running = False
        character_rect.move_ip(0, velocity_y * dt)
        screen.fill(pygame.Color(0, 0, 0, 255))
        screen.blit(character, character_rect)
        pygame.display.flip()

When I run this altered script, I do indeed see the image moving down the screen.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .