]> git.tdb.fi Git - libs/game.git/commitdiff
Remove destroyed entities from the physics simulation
authorMikko Rasa <tdb@tdb.fi>
Sun, 27 Nov 2022 21:48:39 +0000 (23:48 +0200)
committerMikko Rasa <tdb@tdb.fi>
Sun, 27 Nov 2022 21:48:58 +0000 (23:48 +0200)
examples/bassteroids/source/physics.cpp
examples/bassteroids/source/physics.h

index 3c435026e925b057b9eaf7ee3987bd08793153c5..73d858295db7df316f55a7e8396c9312e09c5c81 100644 (file)
@@ -1,5 +1,5 @@
 #include "physics.h"
-#include <algorithm>
+#include <msp/core/algorithm.h>
 #include <msp/game/transform.h>
 #include "physicalentity.h"
 
@@ -12,6 +12,7 @@ Physics::Physics(Game::Stage &s):
        observer(stage.get_event_bus())
 {
        observer.observe<Game::Events::EntityCreated>([this](auto &e){ entity_added(e); });
+       observer.observe<Game::Events::EntityDestroyed>([this](auto &e){ entity_removed(e); });
 
        stage.synthesize_initial_events(observer);
 }
@@ -36,6 +37,27 @@ void Physics::entity_added(const Game::Events::EntityCreated &e)
        }
 }
 
+void Physics::entity_removed(const Game::Events::EntityDestroyed &e)
+{
+       if(Game::Handle<PhysicalEntity> physical = dynamic_handle_cast<PhysicalEntity>(e.entity))
+       {
+               auto i = find_member(entities, physical, &SimulatedEntity::entity);
+               if(i!=entities.end())
+               {
+                       size_t index = distance(entities.begin(), i);
+                       if(index<fixture_count)
+                       {
+                               if(index+1!=fixture_count)
+                                       *i = std::move(entities[fixture_count-1]);
+                               entities[fixture_count-1] = std::move(entities.back());
+                       }
+                       else
+                               *i = std::move(entities.back());
+                       entities.pop_back();
+               }
+       }
+}
+
 void Physics::tick(Time::TimeDelta dt)
 {
        float dt_secs = dt/Time::sec;
index fcf4b0dce534396434b5d6667a654f9aeb73e502..1e7bec3e95cb3e2b0f8d6923a5b1816597d28cd0 100644 (file)
@@ -55,6 +55,7 @@ public:
 
 private:
        void entity_added(const Msp::Game::Events::EntityCreated &);
+       void entity_removed(const Msp::Game::Events::EntityDestroyed &);
 
 public:
        void tick(Msp::Time::TimeDelta) override;