1

可以说我有卡车课。这个类有很多实例,在到达特定点时实例应该“卸载”它的货物 - 根本不移动 N 秒,而其他卡车应该继续移动,除非它们到达它们的卸载点。

我通过将运动矢量设置为(0,0)然后将其重置回原始来完成停止部分。

但是如何在不冻结其他汽车的情况下等待 N 秒呢?从我目前发现的情况来看,我认为我需要以某种方式申请pygame.time.set_timer,但这对我来说真的很困惑。

4

1 回答 1

0

沿着这些路线的东西应该起作用:到达目标时停止卡车(truck.vel = Vector2(0, 0)),然后设置它的waiting_timestart_time属性(我只是在__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版本:

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

    def update(self, dt):
        self.waiting_time -= dt
        if self.waiting_time <= 0:
            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:
        dt = clock.tick(30) / 1000

        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True

        all_sprites.update(dt)
        screen.fill((30, 30, 30))
        all_sprites.draw(screen)

        pg.display.flip()


if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()
于 2017-10-18T01:05:34.733 回答