让我们说我有班级卡车。有这个级别的很多例子,在到达特定点的时候应该“卸载”它的货物 - 根本不会移动N秒,而其他卡车应该继续移动,除非它们到达卸载点。
我通过将移动矢量设置为(0,0)然后将其重置为原始来执行停止部分。
但如何在不冻结其他车辆的情况下等待N秒?从我到目前为止发现的情况来看,我认为我需要以某种方式应用pygame.time.set_timer
,但这对我来说真的很困惑。
答案 0 :(得分:0)
沿着这些方向行事应该有效:到达目标时停止卡车(truck.vel = Vector2(0, 0)
),然后设置其waiting_time
和start_time
属性(我只是在{{{ 1}}方法)。
__init__
这是import pygame as pg
from pygame.math import Vector2
class Truck(pg.sprite.Sprite):
def __init__(self, pos, waiting_time, *groups):
super().__init__(*groups)
self.image = pg.Surface((50, 30))
self.image.fill(pg.Color('steelblue2'))
self.rect = self.image.get_rect(center=pos)
self.vel = Vector2(0, 0)
self.pos = Vector2(pos)
self.waiting_time = waiting_time # In seconds.
self.start_time = pg.time.get_ticks()
def update(self):
current_time = pg.time.get_ticks()
# * 1000 to convert to milliseconds.
if current_time - self.start_time >= self.waiting_time*1000:
# If the time is up, start moving again.
self.vel = Vector2(1, 0)
self.pos += self.vel
self.rect.center = self.pos
def main():
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
all_sprites = pg.sprite.Group()
truck = Truck((70, 70), 4, all_sprites)
truck2 = Truck((70, 300), 2, all_sprites)
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
all_sprites.update()
screen.fill((30, 30, 30))
all_sprites.draw(screen)
pg.display.flip()
clock.tick(30)
if __name__ == '__main__':
pg.init()
main()
pg.quit()
版本:
dt