1 year ago

#322633

test-img

olbloe

vector subscript out of range error in c++ opengl

I am trying to draw a red translated square. I have to translate four points (literally points of square) of vector points (vector<vec4> points) by using for loop.
But it doesn't work and there's a message:

vector subscript out of range error.

#include <gl/glew.h>
#include <gl/freeglut.h>
#include <GL/GL.h>
#include <GL/glu.h>
#include <vector>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>

using namespace std;
using namespace glm;

//drawing square
void DrawBox(vector<vec4> points, vec3 color)
{
    float size = 0.2;

    points.push_back(vec4(-size / 2, -size / 2, 0, 1));
    points.push_back(vec4(-size / 2, size / 2, 0, 1));
    points.push_back(vec4(size / 2, size / 2, 0, 1));
    points.push_back(vec4(size / 2, -size / 2, 0, 1));

    // set point parameters
    glColor3f(color[0], color[1], color[2]);
    glBegin(GL_LINES);

    for (int i = 0; i < 3; i++) {
        glVertex3f(points[i][0], points[i][1], 0);
        glVertex3f(points[i + 1][0], points[i + 1][1], 0);
    }
    glVertex3f(points[3][0], points[3][1], 0);
    glVertex3f(points[0][0], points[0][1], 0);
    
    glEnd();
}

vector<vec4> points;

void DrawScene()
{
    // clear buffer
    glClear(GL_COLOR_BUFFER_BIT);

    DrawBox(points, vec3(1, 1, 1));

    mat4 trans1 = translate(mat4(1), vec3(0.3, 0, 0));
    
    vec4 transformed_p[4];
    for (int i = 0; i < 4; i++)
    {
        transformed_p[i] = trans1 * points[i];
    }
    DrawBox(points, vec3(1, 0, 0));
    glFlush();
}

int main(int argc, char** argv) {
    glutInit(&argc, argv);
    glutCreateWindow("201658");
    glutDisplayFunc(DrawScene);
    glutMainLoop();
    return 0;
}

(I should not change the DrawBox function.)

c++

opengl

vector

glut

glm-math

0 Answers

Your Answer

Accepted video resources