编辑: 要初始化位置数组m_pos[3]
我在构造函数中将其所有值设置为0,然后从main函数调用另一个名为{{1}的函数}它只在3D地图中设置行星的位置:
SetPos()
因此,构造函数采用以下形式:
void SetPos(float x, float z);
void Planet::SetPos(float x, float z)
{
m_pos[0]=x;
m_pos[1]=0;
m_pos[2]=y;
}
这是一个不好的方法吗? (根据需要,我不能直接通过构造函数设置位置。)
ORIGINAL:
我创建了一个名为Planet::Planet()
{
m_pos[0]=0;
m_pos[1]=0;
m_pos[2]=0;
}
的类,它在Planet
中控制一系列行星(Planet
对象)。每个对象都有一个map
,它存储了必须绘制行星的坐标。
行星还拥有一个名为array pos[3]
的函数,该函数负责绘制线条,代表实际行星与其他行星之间的连接。一个行星所连接的行星存储在矢量DrawConnections()
。
由于属性是封装的,std::vector<Planet> connections
类中有一个函数返回行星的位置,称为Planet
,其中GetPos(float* pos)
是指向能够存储行星的数组的指针这个星球的位置。
首先,这些是Planet.h文件的原型和变量声明:
*pos
Planet.cpp的函数public:
void DrawConnections(float radius);
void GetPos(float* position);
private:
float m_pos[3];
std::vector<Planet> m_connection;
如下所示:
DrawConnections()
Planet.cpp的函数void Planet::DrawConnections(float radius) //parameter radius controls width of lines
{
float position[3]={0.0f,0.0f,0.0f}; //array storing the position of the planets
//which we are connecting to
//various OpenGl calls go here
glBegin(GL_LINES); //begins drawing the lines
for(int i=0;i<m_connection.size();i++) //for each planet we are connected to, draw a
//line
{
glVertex3f(m_pos[0],m_pos[1],m_pos[2]); //draws the first point of the line in the
//actual planet
m_connection[i].GetPos(position); //Gets the position of the planet we connect to
glVertex3f(position[0],position[1],position[2]); //draws the second point of the
//in the planet we connect to
}
glEnd(); //ends drawing
//some other OpenGl calls
}
如下所示:
GetPos()
任何行星都有x,z,0坐标都没有。它们中的每一个都有一组(x,y,z)坐标,x和z总是不同于0.
然而,对void Planet::GetPos(float* position)
{
position[0]=m_pos[0]; //copies the data from the position array to
position[1]=m_pos[1]; //the given pointer
position[2]=m_pos[2];
}
的一些调用返回x和z等于0,而其他调用正常。
这导致许多线从行星到屏幕的左下角,没有任何连接。根据我的想法,我认为问题出在GetPos()
。但是,其他类似的绘图函数也使用GetPos()
,并且在GetPos()
函数之前调用它们时效果很好,但是当它们被称为DrawConnection()
被调用时它们似乎会受到影响它好像那个人在被调用时正在修改位置数组的值,从而扰乱了与位置有关的所有其他东西,包括她自己。
作为附加信息,我正在使用Codeblocks和MinGW GNU GCC编译器。我感谢你能给我的任何帮助。
答案 0 :(得分:0)
为什么不这样做?
public:
void DrawConnections(float radius);
const std::vector<float>& GetPos() const {return m_pos;};
private:
std::vector<float> m_pos;
std::vector<Planet> m_connection;