user1697973
user1697973

Reputation:

Opengl Weird Rotation

I'm trying to rotate a simple triangle. The problem is that while it rotates correctly, it decrease its size until it disappears.

Some pieces of my code so far:

// Vertices
GLfloat vertexArray[] = 
{
    1.0f, -1.0f, 0.0f,
    -1.0f, -1.0f, 0.0f,
    0.0f,  1.0f, 0.0f,
};

// Render funcion (called every frame)
void render()
{
    glClearColor(0.0f, 0.0f, 0.4f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);

    glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObj);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertexArray), vertexArray, GL_DYNAMIC_DRAW); 
    glUseProgram(programID); // simple vertex/frag shader

    glDrawArrays(GL_TRIANGLES, 0, 3);

    // Swap buffers
    glfwSwapBuffers();
}

// Update funcion (called every frame before render function)
void update(float elapsedTime)
{
    printf("elapsedTime: %f \r", elapsedTime);

    float static theta = elapsedTime * 0.2f;

    for(int i = 0; i < 9; i+=3)
    {
        vertexArray[i] =   (vertexArray[i] * cosf(theta)) - (vertexArray[i+1] * sinf(theta));
        vertexArray[i+1] = (vertexArray[i] * sinf(theta)) + (vertexArray[i+1] * cosf(theta));
        vertexArray[i+2] = 0;
    }
}

As you can see, I'm rotating every vertex on update function with a for loop. Maybe the best way to do this is using the shader (correct me if I'm wrong), but I wanted to keep things simple here just to illustrate the problem.

Upvotes: 2

Views: 423

Answers (1)

Andy Prowl
Andy Prowl

Reputation: 126402

I believe the problem is, that when you compute vertexArray[i+1] = (vertexArray[i] * sinf(theta)) + (vertexArray[i+1] * cosf(theta)); you are not using the value of vertexArray[i] from the previous iteration, but rather the new vertexArray[i] computed in the first assignment of the for loop.

Try this:

for(int i = 0; i < 9; i+=3)
{
    double tmp = vertexArray[i];

    vertexArray[i] = (tmp * cosf(theta)) - (vertexArray[i+1] * sinf(theta));
    vertexArray[i+1] = (tmp * sinf(theta)) + (vertexArray[i+1] * cosf(theta));
    vertexArray[i+2] = 0;
}

Upvotes: 3

Related Questions