我刚刚制作了一款太空入侵游戏,其中的东西会掉到地上,你必须避免崩溃等。
我成功地创建了 2 个物体同时下落,但我无法让它们以不同的速度执行此操作。
这是第一个对象的属性。
thing_startx = random.randrange(0, display_width-100)
thing_starty = -700
thing_speed = 4
现在它下降了
thing_starty += thing_speed
在每次 while 循环迭代中。
对于下一个对象,我只是将随机数添加到原始 X 和 Y 坐标,以便它获得不同的位置。 (参见下面的函数,如果 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])
现在,我假设我只需要定义
thingy_new = thing_starty + thing_yopt
thingy_new = thingy_new + thing_speed* someconstant #(to make it faster or slower)
不幸的是,事情并非如此。 有人可以向我解释一下为什么我在某种程度上缺乏这个简单的逻辑吗?
最佳答案
最简单的解决方案是将矩形、速度和其他数据组合到代表游戏对象的列表中,然后将这些对象放入另一个列表中并使用 for
循环来更新位置并绘制他们。
您还可以使用字典而不是列表来使代码更具可读性。
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()
如果您知道类如何工作并且您的对象也需要特殊行为,那么最好为您的对象定义一个类。
关于python - 具有不同 "speed"的pygame元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52188563/