【问题标题】:Making the square bigger when it moves移动时使正方形变大
【发布时间】:2019-01-11 17:26:18
【问题描述】:
#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):

【问题讨论】:

  • 为什么不直接修改widthheight
  • 我的 2 美分在这里。尝试学习如何使用顶点和片段着色器。一旦你拥有并理解它们的工作原理,渲染和此类转换就像一百万倍一样容易。

标签: c++ opengl glut coordinate-transformation opengl-compat


【解决方案1】:

使用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();
}

预览:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-15
    • 1970-01-01
    • 2016-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多