Structuring code in WebGL
Most opengl tutorials never ever tell you how to structure your code. The code is usually packed into a single file, which is OK for a tutorial, but fails miserably as soon as you'll want to do anything serious. I've set up one of my projects into 3 javascript files main.js
, game.js
and drawables.js
.
main.js
sets everything up. It binds keyevents, creates the shaders, loads the textures and sets up the game object.
game.js
is where my game object resides. It holds a list of current objects on screen, a list of idle objects off screen and also variables spacifying its state (paused, playing, menu,..), score, gameSpeed (which increases over time) and so on.
The drawables.js
is where my object hierarchy is defined. I could use a new file for each drawable object, but because each .js file is a new http request (and I can't be bothered with minifying and/or asynchronous loading) it seemed like a good compromise. At the bottom of the hierarchy I have a simple Square object.
A Square has a position, a size, velocity and, optionally, a texture. Other drawable objects use the Square object to draw their components. As an example the Player object could be made of two Square objects. One for the main player model and one for the shadow.
Written by Smotko
Related protips
1 Response
I recently had the same realization. I started using Javascript/WebGL after having used the OpenGL in C/C++ for some time, and it has definitely forced me to reevaluate how I structure my code.