检查任何对象worker
是否与其他类(包括Worker
)的对象重叠的正确方法是什么?如果重叠,则应更改轨迹。
pygame
中是否有任何内置函数?任何小例子,将不胜感激。
all_sprites = pygame.sprite.LayeredUpdates()
workers = pygame.sprite.Group()
machines = pygame.sprite.Group()
fences = pygame.sprite.Group()
# create multiple workers
for pos in ((30,30), (50, 400), (200, 100)):
Worker("images/workers/worker_1.png", "images/workers/worker_2.png", pos, all_sprites, workers)
# create multiple machines
Crane("images/machines/excavator.png", (780,390), all_sprites, machines)
# create multiple geo-fences
for rect in (pygame.Rect(510,150,75,52), pygame.Rect(450,250,68,40)):
GeoFence(rect, all_sprites, fences)
答案 0 :(得分:1)
由于您已经使用了精灵和组,因此添加起来非常容易。
看看pygame.sprite.spritecollide
。
我建议像您所说的那样,为所有应该改变轨迹的精灵创建一个组,然后在精灵的spritecollide
函数中使用update
来检查碰撞:
all_sprites = pygame.sprite.LayeredUpdates()
workers = pygame.sprite.Group()
machines = pygame.sprite.Group()
fences = pygame.sprite.Group()
objects = pygame.sprite.Group()
# create multiple workers
for pos in ((30,30), (50, 400), (200, 100)):
Worker("images/workers/worker_1.png", "images/workers/worker_2.png", pos, all_sprites, workers, objects)
# create multiple machines
Crane("images/machines/excavator.png", (780,390), all_sprites, machines, objects)
# create multiple geo-fences
for rect in (pygame.Rect(510,150,75,52), pygame.Rect(450,250,68,40)):
GeoFence(rect, all_sprites, fences, objects)
,并在Worker的更新方法中:
# spritecollide returns a list of all sprites in the group that collide with
# the given sprite, but if the sprite is in this very group itself, we have
# to ignore a collision with itself
if any(s for s in pygame.sprite.spritecollide(self, objects, False) if s != self):
self.direction = self.direction * -1
如果您想要像素完美的碰撞(而不是基于rect的碰撞检测),可以确保将spritecollide
属性设置为mask
,将pygame.sprite.collide_mask
作为第四个参数传递给x=["A", "B", "B", "C", "B", "A", "D", "D", "A", "B", "A", "D"]