找到源自中心顶点的等边三角形网格中的顶点

时间:2013-08-26 02:11:50

标签: c#

我想问一下是否有代码,或者你是否可以帮我写一些(C#,但我猜数学在各处都是一样的。)

我想指定一个中心点,从中心点创建等边三角形网格,并获得这些三角形的顶点。中心点不应该是面中心,而应该是顶点本身。 另一个输入是三角形的大小(即边长)和生成三角形顶点的半径。

背后的原因是我想创建一个网格,它在屏幕/窗口中心很好地居中,尽可能少的代码。我只是找到网格生成代码,但不是“径向向外传播”的例子。

最后,我想让随后更远的顶点以对数方式移位,但我想这只是一个简单的添加,一旦网格代码就在那里。

有人可以帮我吗?谢谢!

2 个答案:

答案 0 :(得分:1)

你需要指定两个东西,一个半径和第一个三角形指向的方向。

  • 半径是从初始点到第一个三角形顶点的距离。所有三角形都具有相同的半径。
  • 方向是弧度的一些规格。我将假设0表示指向右侧(PI将指向左侧)。

找到第一个三角形的顶点可以这样做(伪代码,而不是语言特定的):

float theta = 0; // The direction, 0 means pointing to the right
float thetaInc = TWO_PI/3; // 3 because you want a triangle
for (int i = 0; i < 3; i++) {
    vertX[i] = initialPointX+cos(theta)*radius;
    vertY[i] = initialPointY+sin(theta)*radius;
    theta += thetaInc;
}

有很多方法可以找到相邻三角形的中心点。一种方法是使用相同的代码,但初始化theta = TWO_PI/6,用radius替换foo(参见下面的数学),在for循环中指定相邻三角形的新中心点,然后使用具有适当旋转方向(theta += PI)的相同代码,以找到这些三角形的顶点。

只知道radius

,从一个三角形中心到另一个三角形中心的距离
  • hypotenuse = sqrt(sq(radius)+sq(radius));
  • halfHypotenuse = hypotenuse/2.0;
  • 毕达哥拉斯定理找到从三角形中心到边缘中心的距离:foo = sqrt(sq(radius)-sq(halfHypotenuse));
  • 最终距离= foo*2.0;

查找相邻三角形中心点的代码:

float[] nx = new float[3];
float[] ny = new float[3];

float theta = TWO_PI/6;
float hyp = sqrt(sq(radius)+sq(radius));
float halfHyp = hyp/2.0;
float foo = sqrt((sq(radius)-sq(halfHyp)))*2.0;
for (int i = 0; i < 3; i++) {
    nx[i] = initialPointX+cos(theta)*foo;
    ny[i] = initialPointY+sin(theta)*foo;
    theta += thetaInc;
}

答案 1 :(得分:0)

非常感谢您的回答。我会玩你的代码 - 传播部分肯定会派上用场。

与此同时,我玩过六边形而不是三角形,这些代码在同样的目的下工作得很好。:

//从中心十六进制填充数组,向外移出所需数量的六角环

            for (int i = 0; i < numberOfHexagonRings; i++)
            {
                for (double j = -i; j <= i; j++)
                    for (double k = -i; k <= i; k++)
                        for (double l = -i; l <= i; l++)
                            if ((Math.Abs(j) + Math.Abs(k) + Math.Abs(l) == i * 2) &&   (j + k + l == 0))
                            {
                                positionX = (int)(screenCenterX + ((double)sideLength * (l / 2 + j)));
                                positionY = (int)(screenCenterY + (3/2 * ((double)sideLength / Math.Sqrt(3)) * l));