1

我有这两种方法一个接一个地调用;

m_Fence.Initialise(7);
m_Fence.CreateSquareFence();    

这是他们的每一个细节;

void CFence::Initialise(int size)
{
    m_square_size = size;
}

void CFence::CreateSquareFence()
{
    int l_Vector_Pos = 0;

    //Set initial vector at origin and start of first fence
    CVector3f l_Fence_Position = CVector3f(0.0f,0.0f,0.0f);

    int l_side = 0; // Makes sure only 4 sides get created
    std::string bools[4] = {"plus_z", "plus_x", "minus_z", "minus_x"};
        //Draw 1st fence on 0 x-axis
        while(l_side < 4)
            {
                for(int i=0 ; i<=m_square_size ; i++)
                    {                   
                    //Find which direction it's going and set Fence position and add to vector
                    if(bools[l_side] == "plus_z" &&  i>0)
                        l_Fence_Position += CVector3f(0.0,0.0,beamLength);
                    else if(bools[l_side] == "plus_x" && i>0)
                        l_Fence_Position += CVector3f(beamLength,0.0,0.0);
                    else if(bools[l_side] == "minus_z" && i>0)
                        l_Fence_Position += CVector3f(0.0,0.0,-beamLength);
                    else if(bools[l_side] == "minus_x" && i>0)
                        l_Fence_Position += CVector3f(-beamLength,0.0,0.0);

                    fences[l_Vector_Pos].setPosition(l_Fence_Position);
                    l_Vector_Pos++;

                    //Increase this int to let it know what side we're creating
                    if(i == m_square_size) 
                        {
                            l_side++;
                    }
                }
            }
}

我将 7 传递给它,它最初将m_square_size变量更改为 7,但是当我调用该CreateSquareFence方法时,它最终变为 0,我正在努力寻找原因。

4

1 回答 1

1

将我的评论变成答案

确保fences足够大,这样您就不会超出界限并胜过相邻的记忆(更一般地,调用未定义的行为)。


另一方面,该代码似乎太复杂了。你可以像这样简化它:

void CFence::CreateSquareFence()
{
  int l_Vector_Pos = 0;

  //Set initial vector at origin and start of first fence
  CVector3f l_Fence_Position = CVector3f(0.0f, 0.0f, 0.0f);

  CVector3f offsets[4] = {
    CVector3f(0.0, 0.0, beamLength),
    CVector3f(beamLength, 0.0, 0.0),
    CVector3f(0.0, 0.0, -beamLength),
    CVector3f(-beamLength, 0.0, 0.0)
  };
  for (int l_side = 0; l_side < 4; ++l_side) {
    for (int i = 0; i <= m_square_size; ++i) {
      if (i>0)
        l_Fence_Position += offsets[l_side];
      fences[l_Vector_Pos].setPosition(l_Fence_Position);
      ++l_Vector_Pos;
    }
  }
}
于 2013-11-01T15:38:12.200 回答