[opengl] 画一个可移动的自行车 二维几何变换(平移、旋转、缩放)

[opengl] 画一个可移动的自行车 二维几何变换(平移、旋转、缩放)

1167904-20181115113823897-789092706.png

#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();

}
posted @ 2018-11-15 11:38 Ruoh3kou 阅读( ...) 评论( ...) 编辑 收藏
  • 2
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值