]> git.tdb.fi Git - libs/game.git/commitdiff
Emit events for colliding physical entities
authorMikko Rasa <tdb@tdb.fi>
Sun, 27 Nov 2022 21:45:30 +0000 (23:45 +0200)
committerMikko Rasa <tdb@tdb.fi>
Sun, 27 Nov 2022 21:47:52 +0000 (23:47 +0200)
examples/bassteroids/source/events.h [new file with mode: 0644]
examples/bassteroids/source/physics.cpp
examples/bassteroids/source/physics.h

diff --git a/examples/bassteroids/source/events.h b/examples/bassteroids/source/events.h
new file mode 100644 (file)
index 0000000..65adddb
--- /dev/null
@@ -0,0 +1,18 @@
+#ifndef EVENTS_H_
+#define EVENTS_H_
+
+#include <msp/game/handle.h>
+
+class Collider;
+
+namespace Events {
+
+struct Collision
+{
+       Msp::Game::Handle<Collider> collider1;
+       Msp::Game::Handle<Collider> collider2;
+};
+
+} // namespace Events
+
+#endif
index 67cdf6fe596bbf29199b7af96174c92eecaefc92..3c435026e925b057b9eaf7ee3987bd08793153c5 100644 (file)
@@ -8,6 +8,7 @@ using namespace Msp;
 
 Physics::Physics(Game::Stage &s):
        System(s),
+       event_source(stage.get_event_bus()),
        observer(stage.get_event_bus())
 {
        observer.observe<Game::Events::EntityCreated>([this](auto &e){ entity_added(e); });
@@ -59,6 +60,9 @@ void Physics::tick(Time::TimeDelta dt)
                copy_out<true>(entities[i]);
        for(unsigned i=fixture_count; i<entities.size(); ++i)
                copy_out<false>(entities[i]);
+
+       for(const Collision &c: collisions)
+               event_source.emit<Events::Collision>(entities[c.body1].entity->get_collider(), entities[c.body2].entity->get_collider());
 }
 
 template<bool is_fixture>
index 096e228095fdc94b131ca4796d505bc8e6cb63ad..fcf4b0dce534396434b5d6667a654f9aeb73e502 100644 (file)
@@ -2,16 +2,21 @@
 #define PHYSICS_H_
 
 #include <msp/game/eventobserver.h>
+#include <msp/game/eventsource.h>
 #include <msp/game/events.h>
 #include <msp/game/handle.h>
 #include <msp/game/system.h>
 #include <msp/geometry/angle.h>
 #include <msp/linal/vector.h>
+#include "events.h"
 
 class PhysicalEntity;
 
 class Physics: public Msp::Game::System
 {
+public:
+       using EventSource = Msp::Game::EventSource<Events::Collision>;
+
 private:
        struct SimulatedEntity
        {
@@ -39,6 +44,7 @@ private:
                Msp::LinAl::Vector<float, 2> normal;
        };
 
+       EventSource event_source;
        Msp::Game::EventObserver observer;
        std::vector<SimulatedEntity> entities;
        unsigned fixture_count = 0;