OSG supplies a osg::ShapeVisitor
class for situations such as this one. Create a CenterFinderVisitor
class that extends osg::ShapeVisitor
, overriding each of its virtual member functions to retrieve the center of the corresponding shape. Pass an instance of the CenterFinderVisitor
to the osg::ShapeVisitor
's accept()
member function on the shape instance that you store by pointer inside your class to retrieve the center, like this:
struct CenterFinderVisitor : public osg::ShapeVisitor {
Vec3 center;
virtual void apply (Sphere &s) { center = s.getCenter(); }
virtual void apply (Box &b){ center = b.getCenter(); }
// ...and so on for other shapes
};
Now you can implement your getCenter()
method as follows:
class MyClass {
private:
osg::Shape *shape;
public:
MyClass(string _type) {
// This is for example purposes. Eventually types & mappings will be discovered at run-time.
if (_type == "FOO") {
shape = new osg::Box();
} else if (_type == "BAR") {
shape = new osg::Sphere();
}
}
Vec3 getShapeCenter() {
CenterFinderVisitor cf;
shape->accept(cf);
return cf.center;
}
};
If you are not familiar with the visitor pattern, read this article on wikipedia.