簡體   English   中英

在OpenGL中用極坐標繪制正方形

[英]Draw Square With Polar Coordinates in OpenGL

如何在OpenGL中繪制帶有極坐標的正方形?

我知道這些方程式:

 x = r * cos ( theta ) 
 y = r * sin ( theta )
 r = n * cos ( theta )

我的代碼:

float baseX = width / 2.f; 
float baseY = height / 2.f
int n = 7;
glBegin(GL_POINTS);{
    for (float tempAngle = 0.0 ; tempAngle <= PI/4 ; tempAngle++) {
        radius = n * cos(PI/4);
        x = baseX + radius * cos(tempAngle);
        y = baseY + radius * sin(tempAngle);
        glVertex2f(x, y);
    }
}glEnd();

我希望我們所有人都意識到這只是一個理論上的練習,而不是用OpenGL繪制正方形的合理方法。 但是我仍然認為這可能很有趣,所以我們開始吧。

我認為您的公式不正確。 在坐標系中繪制正方形的右側,該坐標系是x = 1.0處的垂直線。 然后,如果查看距該線上給定點的原點的距離(取決於theta ,則會看到:

cos(theta) = 1.0 / r

很快得出極坐標系中平方的r值:

r = 1.0 / cos(theta)

基於此,這里是使用極坐標繪制正方形的代碼。 side2是正方形邊長的一半:

const float PI_F = static_cast<float>(M_PI);
const unsigned DIV_COUNT = 10;
const float ANG_INC = 0.5f * PI_F / static_cast<float>(DIV_COUNT);

glBegin(GL_LINE_LOOP);

for (unsigned iDiv = 0; iDiv < DIV_COUNT; ++iDiv)
{
    float ang = -0.25f * PI_F + static_cast<float>(iDiv) * ANG_INC;
    float r = side2 / cos(ang);
    glVertex2f(r * cos(ang), r * sin(ang));
}

for (unsigned iDiv = 0; iDiv < DIV_COUNT; ++iDiv)
{
    float ang = -0.25f * PI_F + static_cast<float>(iDiv) * ANG_INC;
    float r = side2 / cos(ang);
    glVertex2f(r * -sin(ang), r * cos(ang));
}

for (unsigned iDiv = 0; iDiv < DIV_COUNT; ++iDiv)
{
    float ang = -0.25f * PI_F + static_cast<float>(iDiv) * ANG_INC;
    float r = side2 / cos(ang);
    glVertex2f(r * -cos(ang), r * -sin(ang));
}

for (unsigned iDiv = 0; iDiv < DIV_COUNT; ++iDiv)
{
    float ang = -0.25f * PI_F + static_cast<float>(iDiv) * ANG_INC;
    float r = side2 / cos(ang);
    glVertex2f(r * sin(ang), r * -cos(ang));
}

glEnd();

我不太確定您的問題是什么意思。 一個正方形具有四個角,在繪制時對應於四個頂點。 固定功能OpenGL使用笛卡爾坐標(實現頂點着色器以攝取極坐標或球坐標並正確轉換為笛卡爾剪貼空間很簡單)。

那到底是什么問題。 我只能看到一種有意義的方式來解釋這個問題: “在極坐標中,正方形的角的坐標是什么?” 但是我看不到您如何在心智模型中將其與OpenGL聯系起來。

我找到了解決方案。

int n = 70;
int i = 1;
glBegin(GL_TRIANGLE_FAN);{
    for (float tempAngle = 0.0 ; tempAngle <= 2 * PI ; tempAngle += PI/8) {
        radius = n * cos(tempAngle);
        x = baseX + radius * cos(tempAngle);
        y = baseY + radius * sin(tempAngle);
        if (i % 2 == 0)
            glVertex2f(x, y);
        i++;
    }
}glEnd();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM