--------------------------------------------用鍵盤移動茶壺--------------------------------------------
#include <GL/glut.h>
float teapotX=0, teapotY=0;
//NEW
void keyboard(unsigned char key, int x, int y)
{
if(key=='a') teapotX+=0.1;
if(key=='b') teapotX-=0.1;
if(key=='c') teapotY+=0.1;
if(key=='d') teapotY-=0.1;
glutPostRedisplay(); //要重畫畫面才會更新
}
//NEW
void display()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPushMatrix();
glTranslatef(teapotX, teapotY, 0);
glutSolidTeapot(0.3);
glPopMatrix();
glutSwapBuffers();
}
int main()
{
glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH);
glutCreateWindow("week10");
glutDisplayFunc(display);
glutKeyboardFunc(keyboard); //NEW
glutMainLoop();
}
-------------------------------------------------------------------------------------------------------
#include <GL/glut.h>
#include <stdio.h>
float teapotX=0, teapotY=0;
void keyboard(unsigned char key, int x, int y)
{
printf("%c %d %d\n", key, x, y);
if(key=='a' || key=='A') teapotX+=0.1;
if(key=='b' || key=='B') teapotX-=0.1;
if(key=='c' || key=='C') teapotY+=0.1;
if(key=='d' || key=='D') teapotY-=0.1;
glutPostRedisplay();
}
void mouse(int button, int state, int x, int y)
{
printf("%d %d %d %d\n", button, state, x, y);
}
void motion(int x, int y)
{
printf("%d %d/n", x, y);
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPushMatrix();
glTranslatef(teapotX, teapotY, 0);
glutSolidTeapot(0.3);
glPopMatrix();
glutSwapBuffers();
}
int main()
{
glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH);
glutCreateWindow("week10");
glutDisplayFunc(display);
glutKeyboardFunc(keyboard);
glutMouseFunc(mouse);
glutMotionFunc(motion);
glutMainLoop();
}
--------------------------------------------用滑鼠轉動+打光--------------------------------------------
#include <GL/glut.h>
#include <stdio.h>
float teapotX=0, teapotY=0;
float angleX=0, startX=0;
float angleY=0, startY=0;
void mouse(int button, int state, int x, int y)
{
printf("%d %d %d %d\n", button, state, x, y);
startX=x;
startY=y;
}
void motion(int x, int y)
{
printf("%d %d\n", x, y);
angleX+= (x-startX); startX = x;
angleY+= (y-startY); startY = y;
glutPostRedisplay();
}
void display()
{
glEnable(GL_DEPTH_TEST);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPushMatrix();
glTranslatef(teapotX, teapotY, 0);
glRotatef(angleX, 0,-1,0);
glRotatef(angleY, -1,0,0);
glutSolidTeapot(0.3);
glPopMatrix();
glutSwapBuffers();
}
void myLight() //打光
{
const GLfloat light_position[] = { 2.0f, 5.0f, -5.0f, 0.0f};
glEnable(GL_LIGHT0);
glEnable(GL_NORMALIZE);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_LIGHTING);
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
}
int main()
{
glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH);
glutCreateWindow("week10");
glutDisplayFunc(display);
glutMouseFunc(mouse);
glutMotionFunc(motion);
myLight();
glutMainLoop();
}



沒有留言:
張貼留言