tutorial 5

In the same way as the last tutorial, we will give the user the option to turn blending off via a menu command. Put the command into your NIB and add the changeBlending action and code.


- (IBAction) changeBlending:(id)sender { if( blending ) { glDisable( GL_BLEND ); glEnable(GL_DEPTH_TEST); [sender setState: NSOffState]; } else { glEnable( GL_BLEND ); glDisable(GL_DEPTH_TEST); [sender setState: NSOnState]; } blending = !blending; }

Now we turn on blending in the initGL method. If we are doing things correctly, with a Z-Buffer, then setting the blend function and enabling blending is enough to make blending work properly. Unfortunately, when you would rather have a small amount of code, it is easier to make your blending work properly by simply turning the depth test off. This means that OpenGL will not do backside culling for you, so you may end up drawing more than you need.


// the following two lines start blending
glBlendFunc(GL_SRC_ALPHA,GL_ONE); glEnable( GL_BLEND );
// unfortunately, the depth test will delete some of the sides if it isn't turned off // the correct way to do this is to sort the polygon
glDisable(GL_DEPTH_TEST); blending = true;

The only thing left is to tell OpenGL that you will have an alpha channel. The closer to 0.0 your last parameter to glColor4f is, the more transparent your object will be.


glColor4f(1.0,1.0,1.0,0.8); [self drawDie];
// some code omitted here
glColor4f(0.5,0.5,1.0,0.5); [self drawDie];

That's all there is to simple blending.


     Download the project builder files

 

return to deep cocoa / cocoagl tutorials