OpenGL---内插动画

21 篇文章 1 订阅
12 篇文章 0 订阅
#include <windows.h> 
#include <gl/Gl.h>
#include <gl/Glu.h>
#include <gl/glut.h>
#include "iostream"
using namespace std;

#pragma comment(lib, "glut.lib")

const int windowWidth = 800;
const int windowHeight = 600;
float t = 0;

struct Point2
{
    float x, y;
    void set(float xx, float yy)
    {
        x = xx;
        y = yy;
    }
};

Point2 a[4], b[4];
const int n = 4;

Point2 Tween(Point2 &a, Point2 &b, float t)
{
    Point2 P;
    P.x = a.x + (b.x - a.x) * t;
    P.y = a.y + (b.y - a.y) * t;
    return P;
}

//画出多边形A和B在t时刻的内插结果
void drawTween(Point2 a[], Point2 b[], int n, float t)
{
    glBegin(GL_LINE_LOOP);
    glColor3f(1, 1, 1);
    for(int i=0; i<n; i++)
    {
        Point2 P = Tween(a[i], b[i], t);
        glVertex2f(P.x, P.y);
    }
    glEnd();
}

void myDisplay()
{
    glClear(GL_COLOR_BUFFER_BIT);
    glColor3f(1, 1, 1);

    //绘制第一个四边形
    glBegin(GL_POLYGON);
    glColor3f(1, 0, 0);
    for(int i=0; i<n; i++)
        glVertex2i(a[i].x, a[i].y);
    glEnd();

    //绘制最后一个四边形
    glBegin(GL_POLYGON);
    glColor3f(1, 0, 0);
    for(i=0; i<n; i++)
        glVertex2i(b[i].x, b[i].y);
    glEnd();

    //绘制中间过程
    t += 0.2;

    if(t <= 1)
    {
        for(float tt=0; tt <= t; tt+=0.2)
        {
            drawTween(a, b, n, tt);
        }
    }
    else
    {
        for(float tt=0.2; tt <1; tt+=0.2)
        {
            drawTween(a, b, n, tt);
        }
    }

    Sleep(400);

    glutSwapBuffers();
    glutPostRedisplay();
}   

void myInit()
{
    glMatrixMode( GL_PROJECTION ); 
    glLoadIdentity();
    gluOrtho2D( 0, windowWidth, 0, windowHeight );

    glClearColor(0, 0, 0, 0);      //背景颜色是黑色
    glViewport(0, 0, windowWidth, windowHeight);

    a[0].set(100, 200);
    a[1].set(200, 200);
    a[2].set(200, 300);
    a[3].set(100, 300);

    b[0].set(650, 200);
    b[1].set(700, 250);
    b[2].set(650, 300);
    b[3].set(600, 250);
}

int main(int argc, char *argv[]) 
{ 
    glutInit(&argc, argv); 
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB); 
    glutInitWindowPosition(50, 50); 
    glutInitWindowSize(windowWidth, windowHeight);
    glutCreateWindow("DEMO"); 
    myInit();
    glutDisplayFunc(myDisplay); 
    glutMainLoop(); 
    return 0; 
}

这里写图片描述

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值