python - 让 Sprite 互相弹开

标签 python pygame collision-detection collision

要下载代码,请按照 link 操作:

背景:

所以,自从我刚接触 pygame 教程以来,我一直在阅读它,并且发现了 Eli Bendersky 著名的 tutorial 。我正在经历第一部分,并试图通过使其成为“社交猫”来添加我自己的天赋。猫们会四处走动,如果它们互相碰触,它们就会互相擦伤,然后分道扬镳。换句话说,Eli 拥有同样的东西,但具有碰撞检测和新的 Sprite 。我认为这将是一个很好的做法。在过去的几天里,我一直在研究碰撞检测以及不同的人如何做到这一点,但我还没有看到一个适合我的场景或类似的东西。我开始意识到我所处的社区是多么小。

目标:

最终,我试图做到这一点,以便当一只猫遇到另一只猫时,发生碰撞的那只猫会向随机方向移动,该方向比当前方向小或大 45 度。

问题:

我正在导入 vec2d,并且我有我的 Cat 类和我的 main 类。我想在主体中进行碰撞检测,因为稍后我将创建一个 GameManager 类来监视正在发生的情况。根据 OOP 的说法,无论如何,猫都不应该互相了解。我一直无法让碰撞检测正常工作。我尝试了几种不同的方法。在这两种情况下,当它们相互接触时都不会发生任何事情。我觉得我想做的事情比我想象的要复杂得多。我怎么把这件事搞砸了?我觉得我在这一方面已经浪费了足够多的时间了。当然,这就是学习的过程。想法?

方式一:

    mainWindow.fill(_white_)
    for cat in cats:
        cat.update(timePassed)
        cat.blitme()
        catsCollided = pg.sprite.spritecollide(cat, catGroup, True)
        print pg.sprite.spritecollide(cat, catGroup, False)

    for cat in catsCollided:
        cat.currentDirection.angle = randint(int(cat.currentDirection.angle - 45), int(cat.currentDirection.angle + 45))   

方式2:

    mainWindow.fill(_white_)
    for cat in cats:
        cat.update(timePassed)
        cat.blitme()
        print pg.sprite.spritecollide(cat, catGroup, False)


    tempCatList = list(cats)
    for catA in cats:
        tempCatList.remove(catA)
        for catB in cats:
            if catA.rect.colliderect(catB.rect):
                cats[cats.index(catA)].currentDirection.angle = randint(int(cat.currentDirection.angle - 45), int(cat.currentDirection.angle + 45))

最佳答案

您的第一种方法是正确的,但是只有一些错误。 Sprite 碰撞是最好的方法。首先,在极少数情况下,您希望 sprite collide 中的第三个参数为 true,除非我完全误解了您的代码是如何执行此操作的,否则您不想使用 True。当您指定 True 时,它​​将在碰撞时自动删除两个 Sprite 。另一件事是您要确保过滤掉自碰撞。基本上,如果一个 Sprite 在自身上运行 Sprite 碰撞,它就会记录与自身的碰撞。关于您的代码的最后一件事是,尽管您的 randint 选择器可能有效(您可能想测试它返回的内容),但 random.choice() 会更适合您正在寻找的内容。实现这些更改后,它看起来像这样:

mainWindow.fill(_white_)
for cat in cats:
    cat.update(timePassed)
    cat.blitme()
    catsCollided = pg.sprite.spritecollide(cat, catGroup, False)   #False makes it so colliding sprites are not deleted
    print pg.sprite.spritecollide(cat, catGroup, False)

for cat in catsCollided:                                           #by the way although this is perfectly fine code, the repetition of the cat variable could be confusing
    if cat != self:                                                #checks that this is not a self collision
        cat.currentDirection.angle = random.choice([int(cat.currentDirection.angle - 45), int(cat.currentDirection.angle + 45])

关于python - 让 Sprite 互相弹开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18874473/

相关文章:

python - 如何使用 Python 列出 REMOTE HOST 目录中的文件?

python - 如何解决pygame闪烁问题

python - 函数重复十次而不是一次 - Pygame Zero

python - 使用对象的 id() 作为哈希值

python - 绘制线点图

python - 为什么这个 'from-import' 因 PyRun_SimpleString 而失败?

JavaScript:碰撞检测

python - 无法在 pygame 中正确执行射弹操作

java - 从 Java 小程序移植到 Android 应用程序后,碰撞检测系统无法工作

Javascript 碰撞检测