c++ - 移动时使正方形变大
问题描述
#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();
}
预习:
推荐阅读
- wordpress - 无法访问子文件夹后端中的 Wordpress 安装
- sql - 查找输出表的 SQL 查询
- apache - 如何将以下简单的 Nginx 重写条件和规则转换为 Apache .htaccess
- javascript - React 变量值永远不会在 find 函数中使用
- python - 安装支持并行 IO 的 netcdf4-python
- performance - 为 Xamarin 项目启用提前编译
- c# - Prism MVVM:“没有为类型定义无参数构造函数”将 ViewModel 绑定到 View 时出错
- c# - 使用 AddUsingPath 将大文件上传到 SharePoint Online
- python - 将 virtualenv 与 pyenv 或 docker 一起使用有什么好处?
- cypress - 从 cypress 版本 5.5.0 获取唯一的验证错误,无论我们输入字段验证的数字是多少,数字已经存在