gpt4 book ai didi

c++ - 移动时使正方形变大

转载 作者:行者123 更新时间:2023-11-30 01:35:26 35 4
gpt4 key购买 nike

#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 来使正方形变大,但我不知道如何在它移动时使其变大。

代码预览:

Square moving to the right

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

Square gets bigger

最佳答案

使用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]。

首先,缩放必须应用于矩形。这意味着它必须是在绘制矩形之前应用于模型 View 矩阵的最后一个操作。最终函数 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();
}

预览:

关于c++ - 移动时使正方形变大,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54151333/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com