osg 地球自转代码
时间: 2025-09-02 12:22:15 AIGC 浏览: 5
使用OpenSceneGraph(OSG)实现地球自转效果,可参考osg实现物体绕自身轴旋转及地球自转且绕太阳公转的思路。要让物体在任何位置围绕自己的轴心旋转,需先保存物体在世界坐标系下的坐标,将物体移动到世界坐标系的原点,在原点旋转后再移回原来的位置。以下为示例代码:
```cpp
#include <osgViewer/Viewer>
#include <osg/Geode>
#include <osg/ShapeDrawable>
#include <osg/MatrixTransform>
#include <osg/AnimationPath>
#include <osg/AnimationPathManipulator>
osg::ref_ptr<osg::Node> createEarth() {
osg::ref_ptr<osg::Geode> geode = new osg::Geode;
osg::ref_ptr<osg::ShapeDrawable> earthShape = new osg::ShapeDrawable(new osg::Sphere(osg::Vec3(0.0f, 0.0f, 0.0f), 1.0f));
geode->addDrawable(earthShape);
return geode;
}
osg::ref_ptr<osg::AnimationPath> createEarthRotationPath() {
osg::ref_ptr<osg::AnimationPath> path = new osg::AnimationPath;
path->setLoopMode(osg::AnimationPath::LOOP);
double time = 0.0;
double deltaTime = 0.1;
double totalTime = 60.0;
for (double t = 0.0; t < totalTime; t += deltaTime) {
osg::Vec3d position(0.0, 0.0, 0.0);
osg::Quat rotation(osg::inDegrees(t * 6.0), osg::Vec3d(0.0, 0.0, 1.0));
path->insert(time, osg::AnimationPath::ControlPoint(position, rotation));
time += deltaTime;
}
return path;
}
int main() {
osgViewer::Viewer viewer;
osg::ref_ptr<osg::MatrixTransform> earthTransform = new osg::MatrixTransform;
earthTransform->addChild(createEarth());
osg::ref_ptr<osg::AnimationPath> earthPath = createEarthRotationPath();
earthTransform->setUpdateCallback(new osg::AnimationPathCallback(earthPath));
viewer.setSceneData(earthTransform);
return viewer.run();
}
```
上述代码首先创建了一个代表地球的球体,然后创建了一个动画路径,让地球绕Z轴旋转。最后将动画路径应用到地球的变换节点上,实现地球自转效果。
阅读全文
相关推荐













