1

openglでフラクタルを作成するのに少し問題があります。これが私の現在のコードです

void generateTree(){
  Point3f startPoint({0.0f,0.0f,0.0f});
  Point3f endPoint({1.0f,0.0f,0.0f});
  float rotation = 90.0f;
  glutWireSphere(0.05, 4, 4);
  _generateTreeBranches(startPoint,1.0f,rotation,0);
}

void _generateTreeBranches(const Point3f& newPosition,
                       float length,
                       float rotation,
                       const int depth)
{
  if(depth > MAX_DEPTH) return;
  cout << "at depth = " << depth << endl;


  if(depth == 0){
      glColor3f(1.0f,1.0f,1.0f);
  }else if(depth == 1){
      glColor3f(1.0f,0.0f,0.0f);
  }else{
      glColor3f(0.0f,1.0f,0.0f);
  }

  glTranslatef(newPosition.x,newPosition.y,newPosition.z);
  glRotatef(rotation, 0.0f, 0.0f, 1.0f);
  drawLine(length);
  glRotatef(-rotation, 0.0f, 0.0f, 1.0f);
  glTranslatef(-newPosition.x,-newPosition.y,-newPosition.z);



  const float newLength = length * BRANCH_LENGTH_DECREASE_FACTOR;
  int nextDepth = depth + 1;
  Point3f nextPosition = {newPosition.x+length, newPosition.y, newPosition.z};

  float leftRotation = rotation + CHILD_BRANCH_ANGLE * nextDepth;
  _generateTreeBranches(nextPosition,newLength,leftRotation,nextDepth);

  float rightRotation = rotation - CHILD_BRANCH_ANGLE * nextDepth;
  _generateTreeBranches(nextPosition,newLength,rightRotation,nextDepth);

}

回転は正しいように見えますが、位置が正しくありません。新しいブランチは、親のブランチの終点から描画されていません。誰かがこの問題を解決するのを手伝ってもらえますか?ここで完全なコードをチェックしてください

4

1 に答える 1

1

nextPositionの式は、現在のブランチが向いている方向を考慮していないため、正しくありません。

 Point3f nextPosition = {newPosition.x+length, newPosition.y, newPosition.z};

次のようになります(正確に確認してください)。

Point3f nextPosition = {newPosition.x+length*cos(rotation), newPosition.y+length*sin(rotation), newPosition.z};

また、glLoadIdentity()を使用して、次のようにマトリックスをすぐにリセットしてください。

glTranslatef(newPosition.x,newPosition.y,newPosition.z);
glRotatef(rotation, 0.0f, 0.0f, 1.0f);
drawLine(length);
glLoadIdentity();

それはあなたがやろうとしていることよりもはるかに明確になります。

于 2012-10-30T07:21:23.043 に答える