c++pure-virtualdelayed-executiontimedelaygameplay3d

Gameplay3D gameplay::TimeListener


Can someone write a concrete example about how to use this function in Gameplay3D:

virtual void gameplay::TimeListener::timeEvent  (   long    timeDiff,
void *  cookie 
)       [pure virtual]

I mean a would like to call a function after t milliseconds but I am not sure how should I write the code.

Here is the documentation: http://gameplay3d.github.io/GamePlay/api/classgameplay_1_1_time_listener.html


Solution

  • There are two approaches based on the documentation, which are both popular C++ patterns that encourage loose coupling.

    1.) The listener approach. In this approach, your class (let's say it's called ObjectManager) would also 'be' ie inherit from, TimeListener. This seems to be the way this framework wants you to go. Have a look at the pure virtual base class "TimeListener"

    2.) The callback approach. This is the second call to "game::Schedule": http://gameplay3d.github.io/GamePlay/api/classgameplay_1_1_game.html#a3b8adb5a096f735bfcfec801f02ea0da This takes a script function. I'm not familiar with this framework, so I can't comment on it too much, you'd need to pass in a pointer to a function that matches the required signature

    Overall, I would do something like this:

    class ObjectManager: public TimeListener
    {
    public:
    
    void OnTimeEvent(long timeDiff, void* cookie)
    {
      // timeDiff is difference between game time and current time
      // cookie is the data you passed into the event. it could be a pointer to anything. 
      // Cast appropriately. remember, it is completely optional! you can pass
      // nullptr!
      MyOtherObject* other = static_cast<MyOtherObject>(cookie);
      // ...
      // handle the event and do the other stuff I wanted to do on a timer.
    }
    
     // my other business logic and all other good stuff this class does.
    
    private:
     // data, other private things.
    }
    
    ....
    

    now, when you want to schedule an event, you can schedule it to be called on your listener:

    ObjectManager myObjectManager; // example only, stack variable. would be invalid.
    
    // Schedule an event to be invoked on the instance noted, with a context of MyOtherObject, in 100 milliseconds.
    gameplay::Game::schedule(100.0, &myObjectManager, new MyOtherObject());
    

    You will need to read the docs to see if you need a pointer to a "Game" object to call schedule on. It doesn't matter if you do it would just be like "game->Schedule(..)" instead then.