These are notes on what happened when I was trying to convert sections of my C++ code to make them more object oriented.
Basic Game UI
My game is a basic clone of the famous Dino Run game. Created using C++ and OpenGL
The problem with my current code:
The problem with my code is that it is based off of the OpenGL ES SDK for Android tutorial. Which means all my code is in one file and is full of global variables and global functions. If I want to expand this game(I do) I need some proper object oriented programming. So I am going to start with this global variable:
GLfloatsquareVertices[]={// First square-0.800f,-0.0375f,// Bottom-left corner-0.650f,-0.0375f,// Bottom-right corner-0.650f,0.0375f,// Top-right corner-0.800f,-0.0375f,-0.650f,0.0375f,-0.800f,0.0375f,// Second square0.85f,-0.0375f,// Bottom-left corner1.0f,-0.0375f,// Bottom-right corner1.0f,0.0375f,// Top-right corner0.85f,-0.0375f,1.0f,0.0375f,0.85f,0.0375f};
and move it into a header file to turn it into this:
classTransformShader{private:std::vector<GLfloat>m_squareVertices={-0.800f,-0.0375f,-0.650f,-0.0375f,-0.650f,0.0375f,-0.800f,-0.0375f,-0.650f,0.0375f,-0.800f,0.0375f,0.85f,-0.0375f,1.0f,-0.0375f,1.0f,0.0375f,0.85f,-0.0375f,1.0f,0.0375f,0.85f,0.0375f};public:std::vector<GLfloat>&getSquareVertices(){returnm_squareVertices;// Returns a reference}};
As you can see from the camera examples above, putting definitions in a header file allows us a greater degree of organization and sharing amongst other files. The immidiate benefits might not be obvious, however, as the program grows and testing becomes more of a priority creating headers files will be more important.
Arrays vs Vectors
As a global variable squareVertices works fine. We can pass functions a pointer to its first value and everything will work like so:
The problems begin when I was moving squareVertices to its own class and trying to pass pointers of it to functions. I suspect the issue was that I was passing a copy of squareVertices and not the actual value its self. So that is when I decided to switch to Vectors. After some googling and reading a section about vectors in The C++ programming language by Bjarne Stroustrup. The general consensus is that usless you have a good reason not to, use a vector. The vector class also allows me to easily return a reference to m_squareVertices. Which seems to of handled the issue I was facing when dealing with the array.
Conclusion
Thank you for taking the time out of your day to read this blog post of mine. If you have any questions or concerns please comment below or reach out to me on Twitter.
Top comments (0)
Subscribe
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Top comments (0)