[opengl] 畫一個可移動的自行車 二維幾何變換(平移、旋轉、縮放)


#include <cmath>
#include "glut.h"
#include "iostream"
using namespace std;

void init(void)
{
	glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
	glClear(GL_COLOR_BUFFER_BIT);
	cout << "init.." << endl;
	glLineWidth(1.0f);
	glColor3f(1.0, 0.0, 0.0);
	glMatrixMode(GL_PROJECTION);//設置投影矩陣
	glLoadIdentity();
	gluOrtho2D(0.0, 600.0, 0.0, 600.0);//二維視景區域 左下角為原點

	//glClear(GL_COLOR_BUFFER_BIT);
	//glMatrixMode(GL_MODELVIEW);
	//glLoadIdentity();

}

int dir = 0;
int angle = 0;
// 繪制車輪
void DrawWheel(double x, double y, double r)
{
	int sec = 10;
	for (int i = 0; i <= sec; i++)
	{
		double delta = 3.1415926*2.0 / sec;
		glBegin(GL_LINE_LOOP);
		glVertex2f(x, y);
		glVertex2f(x + r * cos(delta*i), y + r * sin(delta*i));
		glVertex2f(x + r * cos(delta*(i + 1)), y + r * sin(delta*(i + 1)));
		glEnd();
	}

}

//繪制自行車
void DrawBike() {
	glClear(GL_COLOR_BUFFER_BIT);//清除窗口顯示內容
	glColor3f(1.0f, 0.0f, 0);

	glPushMatrix();
	glTranslatef(100+dir, 124, 0);
	// 橫車桿
	glBegin(GL_LINES);
	glVertex2f(0,0);
	glVertex2f(100,0);
	// 豎車桿
	glVertex2f(70, 0);
	glVertex2f(70, 30);
	// 車把
	glVertex2f(60, 30);
	glVertex2f(80, 30);
	glEnd();
	glPopMatrix();


	// 前車輪
	glPushMatrix();
	glTranslatef(100+dir, 100, 0);
	glRotatef(angle, 0, 0, 1);
	DrawWheel(0,0,25);
	glPopMatrix();

	// 后車輪
	glPushMatrix();
	glTranslatef(200+dir, 100, 0);
	glRotatef(angle, 0, 0, 1);
	DrawWheel(0, 0, 25);;
	glPopMatrix();

	
	glBegin(GL_LINES);
	glVertex2f(0, 75);
	glVertex2f(600, 75);
	glEnd();
	glutSwapBuffers();
}


void keyboard(unsigned char key, int x, int y)
{
	if (key == 'a')// 向左平移
	{
		cout << "左移" << endl;
		dir -= 10;
		angle += 10;
		glutPostRedisplay();//重繪窗口
	}
	if (key == 'd')// 向右平移
	{
		cout << "右移" << endl;
		dir += 10;
		angle -= 10;
		glutPostRedisplay();//重繪窗口
	}
}

void main(int argc, char** argv)
{
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
	glutInitWindowPosition(300, 100);
	glutInitWindowSize(600, 600);
	glutCreateWindow("lab5");


	glutDisplayFunc(DrawBike);
	init();

	glutKeyboardFunc(keyboard);
	glutMainLoop();

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM