Python pygame元素具有不同的;“速度”;
我刚做了一个太空入侵盘游戏,游戏中物体会掉到地上,你必须避免碰撞,等等 我成功地创造了两个物体同时下落,但我不能让它们以不同的速度下落 这是第一个对象的属性Python pygame元素具有不同的;“速度”;,python,pygame,Python,Pygame,我刚做了一个太空入侵盘游戏,游戏中物体会掉到地上,你必须避免碰撞,等等 我成功地创造了两个物体同时下落,但我不能让它们以不同的速度下落 这是第一个对象的属性 thing_startx = random.randrange(0, display_width-100) thing_starty = -700 thing_speed = 4 现在它来了 thing_starty += thing_speed 在每个while循环迭代中 对于下一个对象,我只是将随机数添加到原始的X和Y坐标中,这样
thing_startx = random.randrange(0, display_width-100)
thing_starty = -700
thing_speed = 4
现在它来了
thing_starty += thing_speed
在每个while循环迭代中
对于下一个对象,我只是将随机数添加到原始的X和Y坐标中,这样它就得到了不同的位置。(如果mult==True,则使用下面的cf函数创建两个rect对象)
现在,我想我只需要定义
thingy_new = thing_starty + thing_yopt
thingy_new = thingy_new + thing_speed* someconstant #(to make it faster or slower)
不幸的是,结果并非如此。
有人能给我解释一下为什么我会有这种简单逻辑的缺陷吗?最简单的解决方案是将代表游戏对象的列表中的rect、speed和其他数据组合起来,然后将这些对象放入另一个列表中,并使用
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()
如果您知道类是如何工作的,并且您的对象也需要特殊的行为,那么最好为您的对象定义一个类 如果你给对象起的名字比什么好就好了,因为这很难理解。原则上你的逻辑是正确的,但我猜你没有在代码中完全实现它。如果你的两个对象以不同的速度下落,它们也会有不同的坐标,但在你的示例代码中,你似乎试图将所有信息存储在一组坐标中。实际上,再看一遍,你也可以通过更新
xopt
和yopt
(在你的例子中是yopt+=thing\u speed)得到正确的结果*(someconstant-1)
,但我强烈建议存储每个对象的坐标,而不要将偏移量(opt值)传递给绘图函数。
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()