python - 重置后世界崩溃了

标签 python pygame box2d collision reset

我有这个 PyBox2D 函数,我希望所有的物体都被摧毁,然后当汽车撞到建筑物时重置。 碰撞检测效果很好,世界的破坏也很好,当我尝试重置世界时出现问题。 世界要么崩溃,要么汽车不受控制地移动,或者根本不动。

def _reset():
    if len(box2world.bodies) == 0:
        for building in skyscrapers:
            building.destroy_flag = False


        for wheel in cars[0].tires:
            wheel.destroy_flag = False

        cars[0].destroy_flag = False

        create_buildings()      
        create_car()
        cars[0].control()

box2world = world(contactListener=myContactListener(), gravity=(0.0, 0.0), doSleep=True)

最佳答案

看起来您控制的唯一汽车是 cars[0],即列表中的第一辆车。 当您撞上建筑物并使用 _step() 时,您将 cars[0] 的 destroy_flag 设置为 True,然后销毁它们,然后在 _reset 中将其设置回 false。 此外,当您创建汽车时,您正在附加到汽车。您需要将 cars 重置为空列表:创建新车时也不会更新 car[0] 的位置,仅更新列表中的新车。除了不清空摩天大楼列表之外,同一位置仍然有摩天大楼以及同一位置的汽车[0]。 这会导致永久破坏/重置场景,进而无限期地创建汽车和摩天大楼,从而导致您的世界崩溃。

def _reset():
    if len(box2world.bodies) == 0:
        for building in skyscrapers:
            building.destroy_flag = False


        for wheel in cars[0].tires:
            wheel.destroy_flag = False

        cars[0].destroy_flag = False

        skyscrapers=[]
        cars = []
        #or you could keep your old car and just increase the index
        # to do this, instead of calling car[0], your may want to call car[carnum]
        #before creating your first car you could set the carnum to 0
        #just before creating the new car during reset you would do carnum += 1
        #another way would be instead of appending your car to a list you could do cars=[Car()]

        create_buildings()
        create_car()
        cars[0].control()

关于python - 重置后世界崩溃了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60299853/

相关文章:

Python相同的代码但不同的继承

python - 将 .h 文件中的常量导入 python

c++ - Box2D 创造世界

javascript - 运行时错误 : There is no current event loop in thread 'Thread-1' . - requests_html, html.render()

python - matplotlib - 循环生成箱线图

python - Pygame - 尝试射击时崩溃

python - Pygame rect.center 属性

python - 在不使用 Sprite 的情况下,如何在屏幕底部的移动图像和下落物体之间进行碰撞检测?

android - 如何找到图像的顶点(山)