Question

I'm trying to do a simple Pong game, but I'm running into some issues. Essentially, I have an array of four points with an x & y value meant to represent a hardcoded ball, and I need to get that ball to display properly. I keep crashing when I try to use glDrawArray because the four that I'm passing in the last parameter (meant to draw four vertices) is out of bounds. Any idea why?

In my setup:

//put in vertices for ball
//point 1
ballPosArr[0] = 0.1; //x
ballPosArr[1] = 0.1; //y
//pt 2
ballPosArr[2] = -0.1;
ballPosArr[3] = 0.1;
//pt 3
ballPosArr[4] = 0.1;
ballPosArr[5] = -0.1;
//pt 4
ballPosArr[6] = -0.1;
ballPosArr[7] = 0.1;


//ball position buffer
GLuint buffer;
glGenBuffers( 1, &buffer);
glBindBuffer( GL_ARRAY_BUFFER, buffer);
glBufferData( GL_ARRAY_BUFFER, 8*sizeof(GLuint), ballPosArr, GL_STATIC_DRAW );
_buffers.push_back(buffer); //_buffers is a vector of GLuint's

// Initialize the attributes from the vertex shader
GLuint bPos = glGetAttribLocation(_shaderProgram, "ballPosition" );
glEnableVertexAttribArray(bPos);
glVertexAttribPointer(bPos, 2, GL_FLOAT, GL_FALSE, 0, &ballPosArr[0]);

In my display callback:

GLuint bPos = glGetAttribLocation(_shaderProgram, "ballPosition");
glEnableVertexAttribArray(bPos);

//rebind buffers and send data again
//ball position
glBindBuffer(GL_ARRAY_BUFFER, _buffers[0]);
glVertexAttribPointer(bPos, 2, GL_FLOAT, GL_FALSE, 0, &ballPosArr[0]);
glDrawArrays( GL_POLYGON, 0, 4); //bad access error at 4

In my vshader.txt:

attribute vec2 ballPosition;

void main() {

}
Was it helpful?

Solution

If you use VBOs, which you do, the last argument of glVertexAttribPointer is a relative offset into the buffer, not the CPU address of the buffer. In your case, pass 0 for the last argument, since the vertex data you want to use is at the start of the buffer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top