效果
直接上源码
- 需要包含的头文件很多,这里没全贴上
- 多定义XYZ枚举类
- 代码复制就能用
#include <osg/ShapeDrawable> // osg::ShapeDrawable
typedef enum Axis {
X,Y,Z,NONE
}Axis;
/* @return 返回xyz坐标轴的组节点 */
osg::ref_ptr<osg::Group> makeCoordinate()
{
// 创建空组节点
osg::ref_ptr<osg::Group> group = new osg::Group();
// 精细度类并设置对应精细度 值越小精度也就越小
osg::ref_ptr<osg::TessellationHints> hits = new osg::TessellationHints;
hits->setDetailRatio(10.0f);
// 定义坐标轴长度和半径
float len = 200;
float radius = 10;
// 定义三种颜色
osg::Vec4 blue = osg::Vec4(0.0f, 0.0f, 1.0f, 1.0f);
osg::Vec4 red = osg::Vec4(1.0f, 0.0f, 0.0f, 1.0f);
osg::Vec4 green = osg::Vec4(0.0f, 1.0f, 0.0f, 1.0f);
// 坐标轴圆心为黑体球体
osg::ref_ptr<osg::Sphere> sphere = new osg::Sphere(osg::Vec3(0, 0, 0), radius*1.5);
osg::ref_ptr<osg::ShapeDrawable> sphereDrawable = new osg::ShapeDrawable(sphere.get());
sphereDrawable->setColor(osg::Vec4f(0.0, 0.0, 0.0, 1.0));
group->addChild(sphereDrawable);
for (int i = 0; i < 3; ++i) {
osg::ref_ptr<osg::Cylinder> cylinder = new osg::Cylinder(osg::Vec3(0.0, 0.0, len/2), 10, len); // 创建几何信息对象 (center,radius,height)
osg::ref_ptr<osg::Cone> cone = new osg::Cone(osg::Vec3(0.0, 0.0, len), radius*1.5, radius*3);
osg::ref_ptr<osg::ShapeDrawable> cylinderDrawable = new osg::ShapeDrawable(cylinder.get()); // 创建几何体,几何信息加入到几何体
osg::ref_ptr<osg::ShapeDrawable> coneDrawable = new osg::ShapeDrawable(cone.get());
osg::ref_ptr<osgText::Text> pTextXAuxis = new osgText::Text; // 创建字体节点
osg::ref_ptr<osg::MatrixTransform> axisTransform = new osg::MatrixTransform(); // 创建转换节点
axisTransform->addChild(cylinderDrawable); // 将圆柱圆锥和字体加入转换矩阵节点中
axisTransform->addChild(coneDrawable);
axisTransform->addChild(pTextXAuxis);
cylinderDrawable->setTessellationHints(hits); // 设置精细度
coneDrawable->setTessellationHints(hits);
Axis axis = static_cast<Axis>(i);
switch (axis) {
case X:
axisTransform->setMatrix(osg::Matrix::rotate(osg::inDegrees(90.0), osg::Y_AXIS)); // 绕Y轴旋转90°
cylinderDrawable->setColor(red);
coneDrawable->setColor(red);
pTextXAuxis->setText(L"X轴");
break;
case Y:
axisTransform->setMatrix(osg::Matrix::rotate(osg::inDegrees(-90.0), osg::X_AXIS)); // 绕X轴旋转90°
cylinderDrawable->setColor(green);
coneDrawable->setColor(green);
pTextXAuxis->setText(L"Y轴");
break;
case Z:
axisTransform->setMatrix(osg::Matrix::rotate(osg::inDegrees(90.0), osg::Z_AXIS)); // 绕Z轴旋转90°
cylinderDrawable->setColor(blue);
coneDrawable->setColor(blue);
pTextXAuxis->setText(L"Z轴");
break;
}
pTextXAuxis->setPosition(osg::Vec3(0.0f, 0.0f, len)); // 设置字的位置
pTextXAuxis->setAxisAlignment(osgText::Text::SCREEN); // 设置字一直保持正面朝向屏幕
pTextXAuxis->setCharacterSize(64);
group->addChild(axisTransform.get()); // 将其中单个轴节点加入组节点中
}
return group;
}