pygame elements with different “speed”

2019-07-17 14:28发布

问题:

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 make them doing this with different speed.

This the first object's attributes.

thing_startx = random.randrange(0, display_width-100)
thing_starty = -700
thing_speed = 4

Now it falls by

thing_starty += thing_speed 

in each while loop iteration.

For the next object I just added random numbers to the original X and Y coordinates so it gets it different position. (cf function below to create two rect objects if mult == True)

def things_mult(thingx, thingy, thingw, thingh, color, mult, xopt, yopt, wopt, col2):
    if mult == False:
        pygame.draw.rect(gameDisplay, color, [thingx, thingy, thingw, thingh])
    else:
        pygame.draw.rect(gameDisplay, color, [thingx, thingy, thingw , thingh])
        pygame.draw.rect(gameDisplay, col2, [thingx + xopt, thingy + yopt, thingw + wopt, thingh])

Now, I assume I just need to define

thingy_new = thing_starty + thing_yopt
thingy_new = thingy_new + thing_speed* someconstant #(to make it faster or slower)

Unfortunately, it does not work out like that. Can someone please explain to me why I am somehow shortcoming that simple logic?

回答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 = False
while not done:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            done = True

    for 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.



标签: python pygame