Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/fortran/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何检查对象的重叠?_Python_Pygame - Fatal编程技术网

Python 如何检查对象的重叠?

Python 如何检查对象的重叠?,python,pygame,Python,Pygame,检查任何对象worker是否与其他类(包括worker)的对象重叠的正确方法是什么?如果它重叠,它应该改变轨迹。 pygame中是否有内置功能?任何小例子都将不胜感激 all_sprites = pygame.sprite.LayeredUpdates() workers = pygame.sprite.Group() machines = pygame.sprite.Group() fences = pygame.sprite.Group() # create multiple worker

检查任何对象
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)

因为您已经使用了精灵和组,所以添加起来很容易

看一看

我建议为所有应更改轨迹的精灵创建一个组,如您所说,然后在精灵的
更新
功能中使用
spritecollide
检查碰撞:

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)
在工人的更新方法中:

    # 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

如果您想要像素完美碰撞(而不是基于矩形的碰撞检测),如果您确保精灵具有
遮罩
属性,则可以将第四个参数传递给
spritecollide
,谢谢。你能解释一下这里的
对象是什么吗?@ScalaBoy只是另一个
,包含所有应该触发工人方向改变的对象。请随便找一个更好的名称:-)因此,
对象
指向所有对象,即
围栏
机器
,等等?@ScalaBoy是的,这就是想法。当然,您可以与所有不同的组多次调用
spritecollide
。。。最后,什么是最好的取决于你到底想要什么,有时候没有最好的方法来做某事。