移动时使正方形变大

Making the square bigger when it moves

#include <stdio.h> // this library is for standard input and output
#include "glut.h" // this library is for glut the OpenGL Utility Toolkit
#include <math.h>

float squareX = 0.0f;
float squareY = 200.0f;

static int flag = 1;

void drawShape(void) {
    float width = 58.0f;
    float height = 40.0f;
    glTranslatef(squareX, squareY, 0);
    // test
    // glScalef(0.0, 0.0, 0.0);
    glBegin(GL_POLYGON);
    glColor3f(1.0, 0.0, 0.0);
    glVertex2f(0, 0);
    glVertex2f(width, 0);
    glVertex2f(width, height);
    glVertex2f(0, height);
    glVertex2f(0, 0);
    glEnd();
}

void initRendering() {
    glEnable(GL_DEPTH_TEST);
}

// called when the window is resized
void handleResize(int w, int h) {
    glViewport(0, 0, w, h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0.0f, (float)w, 0.0f, (float)h, -1.0f, 1.0f);
}

int state = 1;

void update(int value) {
    if (state == 1) { // 1 : move right
        squareX += 1.0f;
        if (squareX > 400.0) {
            state = 0;
        }
    }
    glutPostRedisplay();
    glutTimerFunc(25, update, 0);
}

void display() {
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    drawShape();
    glutSwapBuffers();
}

int main(int argc, char** argv) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
    glutInitWindowSize(400, 400);
    glutCreateWindow("Moving Square");
    initRendering();
    glutDisplayFunc(display);
    glutReshapeFunc(handleResize);
    glutTimerFunc(25, update, 0);
    glutMainLoop();
    return(0);
}

我想让正方形在向右移动的同时变大。请参阅下面的第二个 GIF。我知道我需要 glScalef 来使正方形变大,但我不知道如何在它移动时使其变大。

代码预览:

我需要它来做类似的事情(对不起质量,我自己创建了 GIF):

使用 glScale 根据 X 位置缩放矩形 (squareX):

float rectScale = 1.0f + (squareX / 400.0f);
glScalef(rectScale, rectScale, 1.0f);

注意 squareX 在 [0.0, 400.0] 范围内,因此 1.0f + (squareX / 400.0f) 在 [1.0, 2.0] 范围内。

首先必须对矩形应用缩放。这意味着它必须是在绘制矩形之前应用于模型视图矩阵的最后一个操作。最终函数 drawShape 可能如下所示:

void drawShape(void) {
    float width = 58.0f;
    float height = 40.0f;
    glTranslatef(squareX, squareY, 0);

    float rectScale = 1.0f + (squareX / 400.0f);
    glScalef(rectScale, rectScale, 1.0f);

    glBegin(GL_POLYGON);
    glColor3f(1.0, 0.0, 0.0);
    glVertex2f(0, 0);
    glVertex2f(width, 0);
    glVertex2f(width, height);
    glVertex2f(0, height);
    glVertex2f(0, 0);
    glEnd();
}

预览: