首页 > 解决方案 > 重置后世界崩溃

问题描述

我有这个 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)

标签: pythonpygamebox2dcollisionreset

解决方案


看起来您控制的唯一汽车是汽车[0],即列表中的第一辆汽车。当您撞上建筑物并且 _step() 时,您将汽车 [0] 的 destroy_flag 设置为 True,然后将其销毁,然后在 _reset 中将其设置回 false。此外,当您创建汽车时,您将附加到汽车。您需要将汽车重置为空列表:您也不会在创建新车时更新 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()

推荐阅读