Bind velocity_func to member method

Official forum for the Chipmunk2D Physics Library.
Post Reply
con
Posts: 2
Joined: Wed Feb 08, 2012 11:59 am
Contact:

Bind velocity_func to member method

Post by con »

I've recently started using chipmunks and I really like it.
Except for one problem with OOP: Because chipmunk is written in plain C, I'm not able to bind the velocity_func to a non-static member method (C++). I've tried several workarounds so far but hadn't any luck with this.
I understand that pointer to member methods are a different size, then pointer to functions. Had anyone the same problem and found a Solution? Some code:

Code: Select all

class Player{
public:
    Player();
    ~Player();
    void playerUpdateVelocity(cpBody *body, cpVect gravity, cpFloat damping, cpFloat dt);
protected:
private:
    cpBody *playerBody;
};

Player::Player(){
    playerBody = cpBodyNew(1.0f, INFINITY);
    playerBody->velocity_func = playerUpdateVelocity;
}

void Player::playerUpdateVelocity(cpBody *body, cpVect gravity, cpFloat damping, cpFloat dt){
// do something
}
That works only, as if the playerUpdateVelocity method is static (4th line, add "static" to the method declaration). What I want to accomplish: bind it to an member function, so that I can creat multiple "Players". Is this even possbile? Or did I made a fatal code design misstake?

Thanks for any help!
User avatar
slembcke
Site Admin
Posts: 4166
Joined: Tue Aug 14, 2007 7:13 pm
Contact:

Re: Bind velocity_func to member method

Post by slembcke »

Sure, you just have to wrap it with a function. Something like this:

Code: Select all

cpBody *someBodyToLove = cpBodyNew(...);
someBodyToLove->data = myCPPObject;
someBodyToLove->velocity_func = CallVelocityFunc;

CallVelocityFunc(cpBody *body, cpVect gravity, cpFloat damping, cpFloat dt)
{
  ((MyCPPClass *)body->data)->VelocityUpdateMethod();
}
Pretty much the same thing you need to do when wrapping the API for any other language. Nearly every language in existence can use C functions, it's just a question of getting the data you need into them. That's why most callbacks in Chipmunk also take a user defined "data" parameter. In the case of callbacks on bodies, shape, constraints, etc, you have the data pointer on the object that you can use to point back to your "real" object.
Can't sleep... Chipmunks will eat me...
Check out our latest projects! -> http://howlingmoonsoftware.com/wordpress/
con
Posts: 2
Joined: Wed Feb 08, 2012 11:59 am
Contact:

Re: Bind velocity_func to member method

Post by con »

Great, thank you!
Works like a charm!
Post Reply

Who is online

Users browsing this forum: No registered users and 25 guests