Rotate the vertex array (Rotating X or Z breaks everything)

This commit is contained in:
2024-01-11 14:40:19 -05:00
parent e205c581eb
commit 79b2ac2637
3 changed files with 37 additions and 6 deletions

View File

@@ -35,18 +35,20 @@ public:
// William continues to load assets on the first frame.
if (engine->frameCount == 1) {
geometry.load("assets/models/cube.obj");
geometry.scale(0.25f);
geometry.scale(0.5f);
position = {0,-2,0};
}
//Rotate
this->angle.y += 200.0*engine->frameDelta;
this->angle.y = -255*engine->frameDelta;
//this->angle.z = 255*engine->frameDelta;
geometry.rotate(angle);
boundingBox = BoundingBox::calculateAABB(&geometry);
}
void render() override {
glColor3f(0.75,0.75,0.75);
glPushMatrix();
glRotatef(-angle.x,1.0f, 0.0f, 0.0f);
glRotatef(-angle.y,0.0f, 1.0f, 0.0f);
//glRotatef(-angle.x,1.0f, 0.0f, 0.0f);
//glRotatef(-angle.y,0.0f, 1.0f, 0.0f);
glTranslatef(position.x ,position.y,position.z);
geometry.draw();
glPopMatrix();

View File

@@ -5,9 +5,10 @@
#include <fstream>
#include <sstream>
#include <GL/gl.h>
#include <J3ML/LinearAlgebra/Vector3.h>
struct Vertex {
GLfloat x, y, z;
float x, y, z;
GLfloat u, v;
};
@@ -16,6 +17,7 @@ public:
std::vector<Vertex> vertices;
std::vector<unsigned int> indices;
void scale(GLfloat multiplier);
void rotate(LinearAlgebra::Vector3 angle);
void load(const std::string& filename);

View File

@@ -1,6 +1,8 @@
#include <engine/engine.h>
#include <types/vertex.h>
#include <cmath>
void VertexArray::scale(GLfloat multiplier) {
for (auto & vertex : vertices) {
vertex.x *= multiplier;
@@ -51,4 +53,29 @@ void VertexArray::draw() {
glVertex3f(vertices[indices[i + 2]].x, vertices[indices[i + 2]].y, vertices[indices[i + 2]].z);
}
glEnd();
}
}
void VertexArray::rotate(LinearAlgebra::Vector3 angle) {
LinearAlgebra::Vector3 angleRad = LinearAlgebra::Vector3(Math::Radians(angle.x), Math::Radians(angle.y), Math::Radians(angle.z));
for (auto& vertex : vertices) {
// Apply 3D rotation matrices
LinearAlgebra::Vector3 vert;
vert.z = -vertex.x * std::sin(angleRad.y) +
vertex.y * std::sin(angleRad.x) * std::cos(angleRad.y) +
vertex.z * std::cos(angleRad.x) * std::cos(angleRad.y);
vert.x = vertex.x * std::cos(angleRad.y) * std::cos(angleRad.z) +
vertex.y * (std::cos(angleRad.x) * std::sin(angleRad.z) - std::sin(angleRad.x) * std::sin(angleRad.y) * std::cos(angleRad.z)) +
vertex.z * (std::sin(angleRad.x) * std::sin(angleRad.z) + std::cos(angleRad.x) * std::sin(angleRad.y) * std::cos(angleRad.z));
vert.y = vertex.x * std::cos(angleRad.y) * std::sin(angleRad.z) +
vertex.y * (std::cos(angleRad.x) * std::cos(angleRad.z) + std::sin(angleRad.x) * std::sin(angleRad.y) * std::sin(angleRad.z)) +
vertex.z * (std::sin(angleRad.x) * std::cos(angleRad.z) - std::cos(angleRad.x) * std::sin(angleRad.y) * std::sin(angleRad.z));
vert.Normalize();
vertex.x = vert.x;
vertex.y = vert.y;
vertex.z = vert.z;
}
}