1. 旋转缩放
顶点shader:
#version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aColor;
layout (location = 2) in vec2 aTexCoord;
out vec3 ourColor;
out vec2 TexCoord;
uniform mat4 transform; // 用来接收变换矩阵
void main()
{
gl_Position = transform * vec4(aPos, 1.0); // 变换
ourColor = aColor;
TexCoord = vec2(aTexCoord.x, aTexCoord.y);
}
渲染文件:
// ...
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
glm::mat4 getTransformMat()
{
glm::mat4 trans = glm::mat4(1.0f);
trans = glm::rotate(trans, glm::radians(90.0f), glm::vec3(0.0, 0.0, 1.0));
trans = glm::scale(trans, glm::vec3(0.5, 0.5, 0.5));
return trans;
}
//...
// 渲染循环
// ...
// 设置变换矩阵
unsigned int transformLoc = glGetUniformLocation(ourShader.ID, "transform");
glUniformMatrix4fv(transformLoc, 1, GL_FALSE, glm::value_ptr(getTransformMat()));
// ...
// ...
2. 根据时间设置变换矩阵
glm::mat4 getTransformMat()
{
glm::mat4 trans = glm::mat4(1.0f);
trans = glm::translate(trans, glm::vec3(0.5f, -0.5f, 0.0f));
trans = glm::rotate(trans, (float)glfwGetTime(), glm::vec3(0.0f, 0.0f, 1.0f));
return trans;
}
3. 练习
1. 使用应用在箱子上的最后一个变换,尝试将其改变为先旋转,后位移。看看发生了什么,试着想想为什么会发生这样的事情
先位移后旋转(参见上面根据时间设置变换矩阵)
先旋转后位移
2. 尝试再次调用glDrawElements画出第二个箱子,只使用变换将其摆放在不同的位置。让这个箱子被摆放在窗口的左上角,并且会不断的缩放(而不是旋转)。(sin
函数在这里会很有用,不过注意使用sin
函数时应用负值会导致物体被翻转)
使用sin函数,可以看到负值导致翻转
glm::mat4 getTransformMat()
{
glm::mat4 trans = glm::mat4(1.0f);
trans = glm::translate(trans, glm::vec3(-0.5f, 0.5f, 0.0f));
float value = glm::sin((float)glfwGetTime());
trans = glm::scale(trans, glm::vec3(value, value, 1.0f));
return trans;
}
对其取绝对值
glm::mat4 getTransformMat()
{
glm::mat4 trans = glm::mat4(1.0f);
trans = glm::translate(trans, glm::vec3(-0.5f, 0.5f, 0.0f));
float value = glm::abs(glm::sin((float)glfwGetTime()));
trans = glm::scale(trans, glm::vec3(value, value, 1.0f));
return trans;
}