This sample shows us a simple 2d game with only basic OpenGL knowledge: draw lines, timing, ortho view.
Draw Lines
The way to draw lines is the same as draw other primitives, just set GL_LINES or GL_LINE_STRIP into glBegin function, then provide the vertex position with glVertex3fX or other similar function. Here is the code that used to draw two lines:
glBegin(GL_LINES); glVertex2d(-7, 0); glVertex2d( 7, 0); glVertex2d( 0,-7); glVertex2d( 0, 7); glEnd();
Anti Aliasing
glEnable(GL_LINE_SMOOTH).
1) With the same way, we could enable ant aliasing for polygons and points: glEnable(GL_POLYGON_SMOOTH), glEnable(GL_POINT_SMOOTH). As I know, this method will choose and apply some best-fitted algorithms (there are also fast ones), and the final effect may still not good enough.
2) Another method that we could use is GL_MULTISAMPLE, set up multiple sample ant aliasing properties when we create the OpenGL device. With this method, you could get better visual effect but with more calculation. Because you need to calculate multiple pixels 4x or 16x for each pixels instead of only one.
3) We could also use alpha blending to archive the same effect with less calculation. But here we still need to be careful because we will shut down depth writable. This may cause some pixel over draw again and again.
Timing
Using elapsed time to update program is better than using frame count. With timing, we could get a smooth animation or particle engine updating more naturally. Timing also could be used to calculate FPS, sync game play data between powerful computer and less powerful computer.
Ortho View
or ortho projection. This is very useful when we want to draw 2D stuffs like menu, HUD, texture fonts and so on. To set up the ortho view, just go with following code:
glOrtho(0.0f,width,height,0.0f,-1.0f,1.0f);
Play sound
Sound could be divided into streaming background music, voice, 2d or 3d sound effect. For streaming sound, the player will streaming sound while playing. For sound effects, they usually are loaded into main memory before playing. Sound files compressing format, channel numbers, how many sound could be streaming simultaneously, and sound budget, all of those stuffs are need to consider when we want to write code for sound. Here, a very simple way to play sound is like this:
PlaySound("Data/Die.wav", NULL, SND_SYNC);
In addition to those tech points, there is another topic we could continue discuss: game and game play. And you will see how those source code are when all stuffs come together. It is a bit hard to read and not so easily to understand.
The full source code could be downloaded from here.
本文介绍使用基本OpenGL知识进行2D游戏开发的方法,包括画线、抗锯齿、定时、正交视图等技术要点。同时,讨论了如何在游戏开发中应用抗锯齿技术、实现平滑动画及粒子效果,以及设置正交视图绘制菜单、HUD等2D元素。
152

被折叠的 条评论
为什么被折叠?



