osg实现物体绕自身轴旋转及地球自转且绕太阳公转

本文介绍了如何使用osg库实现地球在自转的同时绕太阳公转的效果。通过保存物体原始位置,将其移至原点进行旋转,然后返回原位置的方法,使物体能够围绕自身轴心旋转。详细代码实现中涉及到osg的回调函数技术。

目录

1. 太阳、地球模型

2. 思路说明

3. 代码实现


1. 太阳、地球模型

       我们知道,地球在自转的同时绕太阳公转。这就涉及到地球绕自身轴旋转及绕太阳轴公转,如何用osg实现呢?即效果如下(这里我们假定太阳是静止的):

2. 思路说明

       如果一个模型不在场景的中心点,这时候使用 osg::Matrix::rotate旋转的话,这个对象会围绕场景的中心点进行旋转,会转一个大圈,那么怎么做才能让他在任何位置的时候,围绕自己的轴心进行旋转?解决思路如下:

  1. 先保存物体在世界坐标系下的坐标,即物体在世界坐标系下的中心点坐标
  2. 再将物体移动到世界坐标系的原点。
  3. 在世界坐标系的原点旋转好后,再移动回原来的位置,即步骤1中的提到的坐标。
     
const osg::BoundingSphere& loaded_bs = m_spTrans0->getBound();  
osg::Vec3d center = m_spTrans0->getBound().center();  // 先保存物体中心点坐标
float fX = m_spTrans0->getBound().center().x();  
float fY = m_spTrans0->getBound().center().y();  
float fZ = m_spTrans0->getBound().center().z(); 

osg::Matrix curMatrix = m_spTran
使用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旋转。最后将动画路径应用到地球的变换节点上,实现地球自转效果。
评论 13
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值