让精灵互相反弹

时间:2013-09-18 14:08:09

标签: python pygame collision-detection collision

要下载代码,请按照link

进行操作

背景

所以我一直在阅读pygame教程,因为我是新手,我找到了Eli Bendersky着名的tutorial。我正在经历第一部分,并试图通过制作它来加入我自己的天赋" Social Cats"。猫会四处游荡,如果他们互相碰触,那么他们会互相放牧,分道扬..换句话说,Eli有同样的东西,但有碰撞检测和新的精灵。我认为这将是一个很好的做法。在过去的几天里,我一直在研究碰撞检测以及不同的人如何做到这一点,但我还没有看到一个适用于我的场景或类似的东西。我开始看到我所在的社区有多小。

目标

最终,我试图这样做,当一只猫遇到另一只猫时,碰撞的那只会以一个等于或小于当前方向45度的随机方向熄灭。

问题

我导入了vec2d,我有我的Cat课程和我的主要课程。我想在main中进行碰撞检测,因为稍后我将创建一个GameManager类来监视正在进行的操作。根据OOP,猫不管怎么说都不会相互了解。我一直无法使碰撞检测工作。我尝试了几种不同的方法。在两种方式中,当他们互相接触时都没有任何反应我得到的印象是我想要做的事情比我对它的感知要复杂得多。我怎么搞砸了?我觉得好像我在这方面浪费了足够的时间。当然,这是学习过程。想法?

方式1:

    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))

1 个答案:

答案 0 :(得分:1)

你的第一种方式是正确的,但只有一些错误。 Sprite碰撞是最好的方法。首先,当你想要sprite collide中的第三个参数为true时,极少数情况下,除非我完全误解你的代码是如何做的,否则你不想使用True。指定True时,它会在碰撞时自动删除两个精灵。另一件事是你要确保过滤掉自我碰撞。基本上,如果一个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])
相关问题