This commit is contained in:
blueloveTH 2023-08-12 23:57:17 +08:00
parent a6ca65b66d
commit 926eafb1c8
3 changed files with 18 additions and 5 deletions

View File

@ -70,7 +70,8 @@ struct PyBody{
b2Fixture* fixture; b2Fixture* fixture;
PyObject* node_like; PyObject* node_like;
PyBody(): body(nullptr), fixture(nullptr), node_like(nullptr){} bool _is_destroyed;
PyBody(): body(nullptr), fixture(nullptr), node_like(nullptr), _is_destroyed(false){}
void _gc_mark() { void _gc_mark() {
if(node_like != nullptr){ if(node_like != nullptr){

View File

@ -16,6 +16,7 @@ void PyBody::_register(VM* vm, PyObject* mod, PyObject* type){
body.body = world.world.CreateBody(&def); body.body = world.world.CreateBody(&def);
body.fixture = nullptr; body.fixture = nullptr;
body.node_like = node; body.node_like = node;
body._is_destroyed = false;
return obj; return obj;
}); });
@ -129,10 +130,7 @@ void PyBody::_register(VM* vm, PyObject* mod, PyObject* type){
// destroy // destroy
vm->bind(type, "destroy(self)", [](VM* vm, ArgsView args){ vm->bind(type, "destroy(self)", [](VM* vm, ArgsView args){
PyBody& body = CAST(PyBody&, args[0]); PyBody& body = CAST(PyBody&, args[0]);
body.body->GetWorld()->DestroyBody(body.body); body._is_destroyed = true; // mark as destroyed
body.body = nullptr;
body.fixture = nullptr;
body.node_like = nullptr;
return vm->None; return vm->None;
}); });
} }

View File

@ -124,6 +124,20 @@ void PyWorld::_register(VM* vm, PyObject* mod, PyObject* type){
f(vm, self.world.GetBodyList(), on_box2d_pre_step); f(vm, self.world.GetBodyList(), on_box2d_pre_step);
self.world.Step(dt, velocity_iterations, position_iterations); self.world.Step(dt, velocity_iterations, position_iterations);
f(vm, self.world.GetBodyList(), on_box2d_post_step); f(vm, self.world.GetBodyList(), on_box2d_post_step);
// destroy bodies which are marked as destroyed
b2Body* p = self.world.GetBodyList();
while(p != nullptr){
b2Body* next = p->GetNext();
PyBody& body = _CAST(PyBody&, get_body_object(p));
if(body._is_destroyed){
body.body->GetWorld()->DestroyBody(body.body);
body.body = nullptr;
body.fixture = nullptr;
body.node_like = nullptr;
}
p = next;
}
return vm->None; return vm->None;
}); });