正方体绕轴旋转
只要在旋转立方体的代码上做稍微的改动即可
旋转立方体
本文将立方体立起来旋转,关键在于初始偏转角度的计算
transform = glm::rotate(transform, glm::radians(45.0f) * static_cast<GLfloat>(glfwGetTime()), glm::vec3(0.0f, 1.0f, 0.0f));
transform = glm::rotate(transform, (glm::f32)acos(1 / sqrt(3)), glm::vec3(1.0f, 0.0f, 1.0f));
** main.cpp**
#include <iostream>
#define GLEW_STATIC
#include"Shader.h"
#include<GL/glew.h>
#include<GLFW/glfw3.h>
#include<glm/glm.hpp>
#include<glm/gtc/matrix_transform.hpp>
#include<glm/gtc/type_ptr.hpp>
int main()
{
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
int WIDTH = 800, HEIGHT = 600;
GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT,"Learn OpenGL ", nullptr, nullptr);
int screenWidth, screenHeight;
glfwGetFramebufferSize(window, &screenWidth, &screenHeight);
if (window == nullptr) {
std::cout << "Failed to creat GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
glewExperimental = GL_TRUE;
if (glewInit() != GLEW_OK) {
std::cout << "Failed to initialize GLEW" << std::endl;
glfwTerminate();
return -1;
}
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
Shader shader = Shader("res/shaders/code.vs", "res/shaders/code.fs");
GLfloat vertices[] = {
-0.5f,-0.5f,-0.5f, 1.0f,0.0f,0.0f,
0.5f,-0.5f,-0.5f, 1.0f,0.0f,0.0f,
0.5f,0.5f,-0.5f, 1.0f,0.0f,0.0f,
0.5f,0.5f,-0.5f, 1.0f,0.0f,0.0f,
-0.5f,0.5f,-0.5f, 1.0f,0.0f,0.0f,
-0.5f,-0.5f,-0.5f, 1.0f,0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O;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
while (!glfwWindowShouldClose(window)) {
glViewport(0, 0, screenWidth, screenHeight);
glfwPollEvents();
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
shader.Use();
glm::mat4 transform = glm::mat4(1.0f);
transform = glm::rotate(transform, glm::radians(45.0f) * static_cast<GLfloat>(glfwGetTime()), glm::vec3(0.0f, 1.0f, 0.0f));
transform = glm::rotate(transform, (glm::f32)acos(1 / sqrt(3)), glm::vec3(1.0f, 0.0f, 1.0f));
transform = glm::scale(transform, glm::vec3(0.5f, 0.5f, 0.5f));
GLuint transLoc = glGetUniformLocation(shader.Program, "transform");//找到transform的位置
glUniformMatrix4fv(transLoc, 1, GL_FALSE, glm::value_ptr(transform));//只传一个矩阵,所以变量是1
glBindVertexArray(VAO);
glDrawArrays(GL_TRIANGLES, 0, 36);
glBindVertexArray(0);
glfwSwapBuffers(window);
}
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
glfwTerminate();
return 0;
}