Skip to content Skip to sidebar Skip to footer

Pygame Elements With Different "speed"

I just made a space-invadish game, where things fall to the ground and you have to avoid crashing, etc. I succeeded in creating 2 objects falling down simultaneously but I cannot m

Solution 1:

The simplest solution is to combine the rect, speed and other data in lists which represent your game objects, and then put these objects into another list and use for loops to update the positions and to draw them.

You could also use dictionaries instead of lists to make the code more readable.

import pygame as pg


pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray12')
# The objects consist of a pygame.Rect, the y-speed and a color.
objects = [
    [pygame.Rect(150, -20, 64, 30), 5, pg.Color('dodgerblue')],
    [pygame.Rect(350, -20, 64, 30), 3, pg.Color('sienna1')],
    ]

done = Falsewhilenot done:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            done = Truefor obj in objects:
        # [0] is the rect, [1] is the y-speed.# Move the objects by adding the speed to the rect.y coord.
        obj[0].y += obj[1]

    screen.fill(BG_COLOR)
    # Draw the rects.for obj in objects:
        pg.draw.rect(screen, obj[2], obj[0])
    pg.display.flip()
    clock.tick(60)

pg.quit()

If you know how classes work and your objects also need special behavior, then better define a class for your objects.

Post a Comment for "Pygame Elements With Different "speed""