Hi, there.
I'm having some troubles with my C++ code and I really don't know where it went wrong. Can somebody help me, please?
It was expected to draw a square and change the color when the user press some keys. The window's background should be white and as the user press the keys the color of the square should change from red to blue and when the user press the key again the color should go back to red as you can see it with the code bellow.
Can somebody can help me with that?
Code:
#include <windows.h>
#include <gl/glut.h>
// Função callback chamada para fazer o desenho
void Desenha(void)
{
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
// Limpa a janela de visualização com a cor de fundo especificada
glClear(GL_COLOR_BUFFER_BIT);
// Especifica que a cor corrente é vermelha
// R G B
glColor3f(1.0f, 0.0f, 0.0f);
// Desenha um quadrado preenchido com a cor corrente
glBegin(GL_QUADS);
glVertex2i(30,226);
glVertex2i(226,30);
// Especifica que a cor corrente é azul
glColor3f(0.0f, 0.0f, 1.0f);
glVertex2i(30,226);
glVertex2i(226,30);
glEnd();
// Executa os comandos OpenGL
glFlush();
}
// Inicializa parâmetros de rendering
void Inicializa (void)
{
// Define a cor de fundo da janela de visualização como branca
glClearColor(1.0f,1.0f,1.0f,0.5f);
}
// Função callback chamada quando o tamanho da janela é alterado
void AlteraTamanhoJanela(GLsizei w, GLsizei h)
{
// Evita a divisao por zero
if(h == 0) h = 1;
// Especifica as dimensões da Viewport
glViewport(0, 0, w, h);
// Inicializa o sistema de coordenadas
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
// Estabelece a janela de seleção (left, right, bottom, top)
if (w <= h)
gluOrtho2D (0.0f, 250.0f, 0.0f, 250.0f*h/w);
else
gluOrtho2D (0.0f, 250.0f*w/h, 0.0f, 250.0f);
}
// Função callback chamada para gerenciar eventos de teclado
void GerenciaTeclado(unsigned char key, int x, int y)
{
switch (key) {
case 97:
case 'a':// muda a cor corrente para vermelho
glColor3f(1.0f, 0.0f, 0.0f);
break;
case 118:
case 'v':// muda a cor corrente para verde
glColor3f(0.0f, 0.0f, 1.0f);
break;
case 27:
case 'esc':// fecha a tela
exit(0);
break;
}
glutPostRedisplay();
}
// Programa Principal
int main(void)
{
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(256,256);
glutInitWindowPosition(10,10);
glutCreateWindow("Quadrado");
glutDisplayFunc(Desenha);
glutReshapeFunc(AlteraTamanhoJanela);
Inicializa();
glutMainLoop();
}