在OpenGL中沿坡度绘制图像

时间:2018-08-25 08:38:00

标签: opengl graphics

我正在编写一个程序,该程序可以在两个带有实心圆的点之间画一条线。圈子: -不应互相重叠 -尽可能靠近 -并且每个圆的中心都应该在直线上。

我已经编写了一个生成圆的函数,但是在计算每个圆的位置以使其正确对齐时遇到了麻烦

void addCircles(scrPt endPt1, scrPt endPt2)
{
  float xLength, yLength, length, cSquare, slope;
  int numberOfCircles;

  // Get the x distance between the two points
  xLength = abs(endPt1.x - endPt2.x);

  // Get the y distance between the two points
  yLength = abs(endPt1.y - endPt2.y);

  // Get the length between the points
  cSquare = pow(xLength, 2) + pow(yLength, 2);
  length = sqrt(cSquare);

  // calculate the slope
  slope = (endPt2.y - endPt1.y) / (endPt2.x - endPt1.x);

  // Find how many circles fit inside the length
  numberOfCircles = round(length / (radius * 2) - 1);

  // set the position of each circle
  for (int i = 0; i < numberOfCircles; i++)
  {
     scrPt circPt;
     circPt.x = endPt1.x + ((radius * 2) * i);
     circPt.y = endPt1.y + (((radius * 2) * i) * slope);

     changeColor();
     drawCircle (circPt.x, circPt.y);
  }

这是上面的代码产生的:

img

我非常确定问题在于这条线,它设置了圆的y值:

circPt.y = endPt1.y + (((radius * 2) * i) * slope);

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:1)

我建议将线的方向计算为unit vector

float xDist = endPt2.x - endPt1.x;
float yDist = endPt2.y - endPt1.y;

float length = sqrt(xDist*xDist + yDist *yDist);
float xDir   = xDist / length;
float yDir   = yDist / length;

计算从一个中心点到下一个中​​心点的距离,numberOfSegments是截面的数目而不是圆的数目:

int numberOfSegments = (int)trunc( length / (radius * 2) );
float distCpt = numberOfSegments == 0 ? 0.0f : length / (float)numberOfSegments;

通过将矢量与直线的起点相加来计算圆的中心点。向量点沿着线的方向及其长度,由两个圆之间的距离乘以圆的“索引”给出:

for (int i = 0; i <= numberOfSegments; i++)
{
   float cpt_x = endPt1.x + xDir * distCpt * (float)i;
   float cpt_y = endPt1.y + yDir * distCpt * (float)i;     

   changeColor();
   drawCircle(cpt_x , cpt_y);
}   

请注意,一行的最后一个圆圈可能会被下一行的第一个圆圈重绘。您可以通过更改for循环的迭代表达式来更改它-将<=更改为<

for (int i = 0; i < numberOfSegments; i++)

在这种情况下,在行尾根本不会画任何圆圈。