• BIT-101 Blog

  • Cocos2d – 2D OpenGL for the iPhone made Easy. Part 1.

17th May 2009

Cocos2d – 2D OpenGL for the iPhone made Easy. Part 1.

posted in Flash, Objective C, iPhone |

[NOTE: I checked the cocos2d source out through svn, which I discovered gives you version 0.8. If you download the source, it looks like the latest version available is 0.7.2. I'm not sure how many differences you'll run into, but the first few comments below will show you at least one. But the solution is there as well.]

I've been working on iPhone dev obviously, and doing some games. I've fooled around with OpenGL a bit, but nothing serious. Been going through Jeff LaMarche's OpenGL tutorials, which are fantastic. But for a lot of my purposes, I don't really need the heavy 3D stuff. I really just need something that would do 2D with the power and speed of OpenGL. My last game, Vector Blocks was actually done fully in Cocoa, which I got away with because there's really only a single object animating at any given time. For any more complex animation, Cocoa would pretty much die. The problem with OpenGL is it's just so low level, you'd end up writing a ton of code just to get your game character and objects on the screen and moving around, even before you started to think about the actual mechanics of the game.

So I heard mention of cocos2d and went over to Google Code to check it out.

http://code.google.com/p/cocos2d-iphone/

I have to say, I'm pretty impressed. It is just what I was looking for. If you are a Flash / ActionScript developer coming into the iPhone world to make games, this is a dream come true. Basically, it gives you a bunch of objects that encapsulate drawing 2D textures via OpenGL. I shouldn't have to say this, but cocos2d is NOT a 3D package. There are a few little 3D tricks in there, but for the most part, that "2d" in its name is there for a purpose.

To get started, go to the Google Code link above and download or check out the source. I've actually created an XCode template that will give you a cocos2d ready application. I say cocos2d because I didn't actually include the library in the template. You'll have to add that to the project yourself. That way I don't have to worry about updating the template whenever the library changes. You can get the template here:

http://www.bit-101.com/iphone/Cocos2DReadyApplication.zip

Unzip that into your XCode templates directory, which is

/Developer/Platforms/iPhoneOS.platform/Developer/Library/Xcode/Project Templates/Application/

Now you should be able to create a new project and choose a Cocos2D Ready Application.

There are instructions in the project, but the two steps you need to do to start coding are:

1. Add the cocos2d classes to the project.
2. Add the fps_image.png to the Resources group of the project.

For step 1, do NOT add the whole cocos2d folder you downloaded or checked out. Just add the cocos2d subdirectory. Later you might want to add additional packages such as cocoslive or the experimental stuff. But minimally you'll need the cocos2d dir. For both of these steps, you can choose to either copy the files over into your project, or just access them from wherever you have them stored. It shouldn't matter to XCode.

For step 2, this png can be found in the Resources/Images folder of the library.

If you've gotten this far, you're ready to start writing some cocos2d. The first thing you need to know about is the Director. This is a well named object. It directs everything that happens. It's a singleton, so you access it via [Director sharedDirector]. If you go to the main app delegate file in your project you'll see some commented out code ready for you to implement. This sets up the Director for use.

C:
  1. [[Director sharedDirector] setDeviceOrientation:CCDeviceOrientationLandscapeLeft];
  2. [[Director sharedDirector] attachInWindow:window];

This is pretty obvious. It tells cocos2d that you want to run in landscape mode, and adds the director to the main application window so it can display stuff on the screen.

The next thing you need to know about are Scenes. Scene is another class in the library. You can think of it kind of like states or views in Flex view stack. At any one time you have a single scene running. You can display a scene by calling the runWithScene method of the Director. You can also push a scene onto the Director, which will save the current scene in a stack, or pop a scene off the Director's stack, which will display the previously pushed stack. Or you can simply replace a scene with a new scene.

So you might have a splash or intro scene, a menu scene, a game scene or maybe multiple level scenes, a high score scene, etc. You just replace or push/pop each scene as needed. Like Flex states, you can use transitions to move between scenes.

So let's make a scene! Right in the main app delegate class's applicationDidFinish launching method, just uncomment the code in the template:

C:
  1. - (void)applicationDidFinishLaunching:(UIApplication *)application {
  2.     window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
  3.     [window setUserInteractionEnabled:YES];
  4.     [window setMultipleTouchEnabled:YES];
  5.    
  6.     [[Director sharedDirector] setDeviceOrientation:CCDeviceOrientationLandscapeLeft];
  7.     [[Director sharedDirector] attachInWindow:window];
  8.    
  9.     [window makeKeyAndVisible]
  10.    
  11.     Scene *scene = [Scene node];
  12.     [[Director sharedDirector] runWithScene:scene];
  13. }

Don't forget to add the import statements for cocos2d.h and Scene.h. (These are actually in the template, just uncomment them.)

If you run or debug this now, you'll see... NOTHING! Obviously, because we haven't displayed anything. So let's add something. A background image anyway.

You can easily add an image by creating a Sprite and calling addChild on the Scene. (See, I told you you Flash guys would like this!) First create a 480x320 pixel png file and add it to the Resources folder of your project. I called mine "background.png". You can see it here:

background

Now change the last few lines of code at the end of the applicationDidFinishLaunching method to look like this:

C:
  1. Scene *scene = [Scene node];
  2. Sprite *background = [Sprite spriteWithFile:@"background.png"];
  3. background.position = ccp(240, 160);
  4. [scene addChild:background];
  5. [[Director sharedDirector] runWithScene:scene];

What we've done is create a new Sprite using the background.png image, positioned it in the center of the screen, and added to the scene. A few things about the positioning. You see we are calling a function named "ccp". This is nothing more than a macro to CGPointMake. Saves you a few key clicks. Also, notice that by default, a sprite's "registration point" is in its geometric center. So when we set it to the center of the screen, it will be centered in the center, thus filling the whole screen. You can change the registration point via a property called anchor, but we don't need to just yet.

So run this, and you'll have a beautiful image like this:

background2

Er... what happened to my nice gradient? Well, you can go to the cocos2d mailing list archives and search "gradient" and you'll see this is a known issue that has supposedly been fixed, but I sure still see it. What is supposed to fix it is adding this line as the first call to the Director:

C:
  1. [[Director sharedDirector] setPixelFormat:kRGBA8];

Unfortunately, this doesn't help for me. I still get the ugly banding. Fortunately, I was able to hack into the source code with some hints from the mailing list and at least make a local fix. What I changed is in the Texture2d.m file, around line 193 in the current release. There's a line that says:

pixelFormat = defaultAlphaPixelFormat;

If you change that to read:

pixelFormat = kTexture2DPixelFormat_RGBA8888;

Your gradients will work just fine. Now, I don't know what other repercussions this "fix" may have, so use it at your own risk. Or, research it some more, come up with a real fix and submit it to the team.

Disregard that crossed out stuff. I found a better way to handle this here.

Well, that's about it for now. Next installment, we'll actually make something move!

Oh, just in case there's any confusion, here's the whole applicationDidFinishLaunching method:

C:
  1. - (void)applicationDidFinishLaunching:(UIApplication *)application {
  2.     window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
  3.     [window setUserInteractionEnabled:YES];
  4.     [window setMultipleTouchEnabled:YES];
  5.    
  6.     [[Director sharedDirector] setPixelFormat:kRGBA8];
  7.     [[Director sharedDirector] setDeviceOrientation:CCDeviceOrientationLandscapeLeft];
  8.     [[Director sharedDirector] attachInWindow:window];
  9.    
  10.     [window makeKeyAndVisible]
  11.    
  12.     Scene *scene = [Scene node];
  13.     Sprite *background = [Sprite spriteWithFile:@"background.png"];
  14.     background.position = ccp(240, 160);
  15.     [scene addChild:background];
  16.     [[Director sharedDirector] runWithScene:scene];
  17. }

Post to Twitter

This entry was posted on Sunday, May 17th, 2009 at 6:09 pm and is filed under Flash, Objective C, iPhone. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

There are currently 23 responses to “Cocos2d – 2D OpenGL for the iPhone made Easy. Part 1.”

  1. 1 On May 17th, 2009, Chris Lyons said:

    This is super cool, thanks a ton! Definitely going to help ease the transition from AS3 to objective-c ;-) I’m having an issue with this line:

    [[Director sharedDirector] setDeviceOrientation:CCDeviceOrientationLandscapeLeft];

    error: ‘CCDeviceOrientationLandscapeLeft’ undeclared (first use in this function)

    ended up using this:

    [[Director sharedDirector] setLandscape: YES];

    seems to get the job done. probably a stupid newbie mistake on my part but figured i’d let you know just in case.

  2. 2 On May 17th, 2009, Matthew Wallace said:

    Hey Keith thanks as always for this great find. I am walking through the steps now and I was getting an error with line

    6.[[Director sharedDirector] setDeviceOrientation:CCDeviceOrientationLandscapeLeft];

    says that it is an undeclared function or whatever so I changed it to the following

    [[Director sharedDirector] setLandscape:YES];

    builds fine and turns the simulator to landscape. Wondering if I may have missed a step or maybe cocoas2d changed the source code or maybe I just missed something in your example.

    Anyway thanks again I just wanted to add commit in case someone else ran into this.

  3. 3 On May 17th, 2009, kp said:

    Matt, are you sure you have the latest source? Mine gives a warning that setLandscape is deprecated.

  4. 4 On May 17th, 2009, kp said:

    Just added a note to the top of the post. The svn checkout is for version 0.8, whereas the download is 0.7.2. That’s the difference. So if you are using 0.7.2, yeah, use “setLandscape”.

  5. 5 On May 17th, 2009, cocos2d Tutorials - TOC | BIT-101 Blog said:

    [...] Part 1 Part 2 Part 3 [...]

  6. 6 On May 18th, 2009, Matthew Wallace said:

    Yeah I figured when I got the error that you where using the svn checkout. So heads up to everyone if setLanscape is deprecated that means it is going away and you should use the svn checkout.

  7. 7 On May 18th, 2009, John said:

    Having researched unity and a couple of others over the weekend, I was literally going to dive-in with cocos today, you are a mind reader.

    Thanks!

  8. 8 On May 18th, 2009, Matthew Wallace said:

    I downloaded the latest source and now I am getting an Terminating Due To Uncaught exception if I run it and sometimes it crashes. I am pretty sure that my code is exactly the same other than the version of cocos2d that I am using.

  9. 9 On May 18th, 2009, kp said:

    does it say where or what the exception is?

  10. 10 On May 18th, 2009, Dan said:

    Optionally, instead of editing Texture2d.m you can edit the following line in Texture2d.h:

    #define kTexture2DPixelFormat_Default kTexture2DPixelFormat_RGBA4444

    to read

    #define kTexture2DPixelFormat_Default kTexture2DPixelFormat_RGBA8888

  11. 11 On May 18th, 2009, kp said:

    That does seem like a better idea, Dan.

  12. 12 On May 18th, 2009, Mike said:

    I ran across this as well, and was able to fix it by loading the “Default.png” and “Icon.png”, in addition to the “fps_images.png” into my project resources. It seems that the splash screen when Coco2D loads up expect these pngs.

    -Mike

    On May 18th, 2009, Matthew Wallace said:
    I downloaded the latest source and now I am getting an Terminating Due To Uncaught exception if I run it and sometimes it crashes. I am pretty sure that my code is exactly the same other than the version of cocos2d that I am using.

  13. 13 On May 18th, 2009, イナヅマtvログ » iPhone SDK, BIT-101 の開発ヒントエントリー said:

    [...] Cocos2d – 2D OpenGL for the iPhone made Easy. Part 1. Cocos2D – Part 2 iPhone SDKようのゲームフレームワーク Cocos2d のTips、どこまで続くんだろう期待大。 [...]

  14. 14 On May 18th, 2009, Fix for cocos2d color banding | BIT-101 Blog said:

    [...] my first tutorial, I brought up an issue with color banding in gradient pngs used in Sprites in cocos2d. I mentioned [...]

  15. 15 On May 19th, 2009, Matthew Wallace said:

    Exception Caught issue…. @kp yeah I am an idiot. I started from scratch and forgot to put the fps_images.png back in the project and it was throughing an exception because it could not find the file.

    Not totally used to debugging in xcode just yet :)

  16. 16 On June 1st, 2009, Myspace: Cocos2d-iPhone said:

    [...] to Cocos2d iPhone Monocles Studio Intro Collision particle Great site with lots of simple examples Game walkthrough Sapus Tongue [...]

  17. 17 On July 20th, 2009, Yasuo said:

    I’ve found little change of cocos2d library.

    [[Director sharedDirector] setDeviceOrientation:CCDeviceOrientationLandscapeLeft];

    [[Director sharedDirector] setLandscape:YES];

    And, it works fine now.
    Thank you for this tutorial. It helped so much. I’ll continue reading.

  18. 18 On July 21st, 2009, money said:

    Thanks for your tutorials.
    I make a problem. I only add the cocos2d classes and uncomment #import “cocos2d.h”, #import “Scene.h”.

    It is succeeded when i build it. But it cannot show in iPhone Simulator. It show:

    Error from Debugger: Failed to launch simulated application: Unknown error

  19. 19 On July 22nd, 2009, Julia said:

    I was getting a Terminating Due to Uncaught Exception as well, whether I used 0.8 or 0.7.2. Loading the “Default.png” and “Icon.png” as Mike said, and it helped, but it still did not run. I added “background.png” also, and that fixed it. Although now I have a picture and not a gradient…

  20. 20 On August 3rd, 2009, Benjamin said:

    Hi Keith,

    Greatly appreciate you taking the time to write this up for us! I love your books. Your ActionScript Animation books got me started making Flash games years ago.

    Cheers,
    Ben

  21. 21 On August 13th, 2009, Quypv said:

    Thanks you very much! your tutorials hepl me full.

  22. 22 On August 29th, 2009, [iPhone] cocos2dを静的ライブラリ化して使う : boreal-kiss.com said:

    [...] 個人的にはFlash的に操作できるという点が一番の恩恵だと思っており、最近はXcodeのプロジェクト作成時にcocos2d用テンプレートしか使っていない。テンプレートを使うのであれば例えばCocos2d – 2D OpenGL for the iPhone made Easy. Part 1.に簡素なものがある。自分で作るのであれば【Xcode】設定しておくと便利なカスタマイズいろいろが参考になる。 [...]

  23. 23 On September 7th, 2009, Ben said:

    Thanks for the great tutorial. I found that I also had to add zlib, as it’s currently a dependency in Cocos2d 8.1.
    This can be done by following this help on Stack Overflow: http://stackoverflow.com/questions/289274/error-when-import-zlib-in-iphone-sdk

    Now to read part 2..

Leave a Reply

Who is reading BIT-101?

Copyright ©2009 by Keith Peters. All rights reserved. This means that you may not reprint or repost the contents of this site without express written permission of the author.


  • Calendar

  • February 2010
    M T W T F S S
    « Jan    
    1234567
    891011121314
    15161718192021
    22232425262728
hoodia order buy Levitra Plus betablockers weight loss information buy pills without a prescription arthritis menopause ambien doses cat's eye health information on cholesterol cialis online order valtrex cheapest phentermine onlin e increase breast size lower blood sugar immediately terramycin which is better cialis or viagra buy cheap cialis reduce cholesterol naturally new blood pressure treatment products for back pain cheapest cialis index will levitra help piroxicam 20 mg order viagra online in germany buy tadalafil online buy levitra onlines how to naturally lower cholesterol buy generic viagra where to buy soma anti allergic drug levothyroxine dogs new hair loss treatmen buy levitra pain meds buy cheap malaria therapy weight loss after baby asthma medications chronic snoring viagra gel prostate cancer cures order viagra cialis alprazolam men health natural cure arthritis immune system support diet medicine cialis approval lipitor effects where can i buy arthritis drugs overactive bladder in men self help weight loss natural cholesterol control ativan medication cialis approval best cure for snoring breast enhancing pills order prozac celebrex pharmacy buy levitra onlines premature ejaculation cure confidence hypnotherapy free stop smoking bust enhance diet weight loss supplements skin fungal infection valium with no prescription viagra with out prescription breast enhancement products alpha blocker medications azithromycin 250mg skin disease chronic heart failure medicines dog care products buying cialis online gerd in children antibiotics to buy my drug store muscle building diet drugs affecting levitra anti anxiety medications really large breast enhancement help for constipation ulcers stomach drugs for high blood pressure selling pet products buy pain medicine viagra online overnight fucidin ointment generic zyrtec prices soft tab cialis smoking treatment dog products online weight loss solution cialis on line blue pills weight loss diet pill nitroglycerin sublingual floxin prevention of heart attack imuran order gasex vermox treatment of depression Viagra On Line buy generic cialis professional tooth whitening kits to buy valium 2mg treatment for hypertension ultram cheapest online stores hair loss products cheap weight loss diovan prescription malaria preventative taurine treating prostate cancer immune system support natural constipation cure phentermine no prescription fast delivery purchase meds without prescription buy plendil diet drug taking viagra after cialis protonix cheapest generic cialis online viagra levitra cialis yohimbe benefits muscle mass gain diet and health products medical treatment for insomnia buy blood pressure meds buy celexa levaquin interactions blood pressure drug skin disorder where can i buy arthritis drugs natural breast enhancer acute pain control online diazepam natural acne remedy antifungal strategies triphala pravachol online how can i stop smoking breast enhancement natural nautral breast enhancement beta blocker medications wellbutrin dosages order viagra cialis lower high blood pressure mass muscle phentermine from canada how to loss weight osteoporosis bone health lipitor use dog medication drug allergies buy diazepam buyviagra cialis phentermine 37.5 mg zestril medication parkinsons treatment generic revatio free nexium cosmetic dentistry tooth whitening avalide generic buy cheap tadalafil uk simvastatin tablets buy cialis online in usa breast pain cat care ovulating clomid medical skin care lines viagra to canada viagra or cialis cheap cialis tramadole buy azulfidine drugs used for cancer ear pain oral ketoconazole raloxifene evista taurine sex with levitra stop smoking today heart failure natural cholesterol control protonix dose oxybutynin 5mg irritable bowel syndrome treatments new treatment for hepatitis c cheap prescription drugs viagra online prescription depression therapy buy sumycin menopause treatment hair loss treatments medication pletal what is a natural antibiotic viagra purchase synthroid tablets generic prilosec lipitor cat health info discount vitamin cholesterol and health bacterial diarrhea weight loss medicine new treatment for depression removing retention fluids diuretic medicines soma 250mg cat anxiety loss weight online pharmacy viagra buy phentermine without a prescription herbs for breast growth cymbalta dosage fast weight loss supplement arthritis menopause levitra online order cheapest place to buy phentermine cold flu medications for nausea buy ultram where pills for acne free weight loss programs help with anxiety improve skin valium 2mg urinary tract health cat urinary tract disease crestor dosage drug zofran calan zyrtec buy nirdosh dosage digoxin buy pain patch acomplia alendronate cialis best price cheap wellbutrin small dog products depression medicine sildenafil dosage dog health depression and anxiety lamictal withdrawal viagra, levitra and cialis online drug buy bone maker strontium cures for hair loss nitroglycerin tablets natural arthritis treatment arimidex buy buy energy patch how to treat a yeast infection viagra herb alternative viagra cialis levitra order sublingual cialis cialis comparison breast lift augmentation seroquel for depression carisoprodol mg new treatment for depression cialis soft tabs safe sleep aid severe leg muscle pain natural weight loss gabapentin medication what is ambien clozapine medication viagra online ordering cures for hair loss free weight loss help buy viagra levitra pet treats order plan b diabetes type 2 phentermine risk ultram er side effects treatment for hepatitis b constipation cures drugs used in treating depression leg pain buy cheap generic cialis anti anxiety meds hypnotherapy for weight loss motilium body building fitness dog skin relieve upper back pain cures for high blood pressure cardura celecoxib Viagra Online Cheap cheap bactrim ambien online lamisil cost infertility meds progesterone clomid osteoporosis hormon urinary tract infection symptoms hypnotherapy for health how to buy viagra online joint pain cure online allegra buy generic cialis uk generic abilify cures for lung cancer new treatments for lung diseases pain meds buy cheap treatment for dry skin disease of the skin nexium drug free stop smoking buy tooth whitening products viagra tablet naprosyn dosage women's fertility male sexual power carisoprodol purchase asthma attack treatment estradiol pills phentermine from canada pet health care hair loss products online astelin generic cheap estrace free weight loss program buy rimonabant relieve lower back pain lexapro prescription new breast cancer drug buying ambien best online viagra scams home scabies treatment hair loss in woman buy generic cialis uk eye drop gabapentin medication amitriptyline uses ultram no prescription natural pain cures buy cla products back pain lowest price generic viagra pain meds buy cheap mg buy phentermine acne skin care cialis rx weight loss and fitness nitrofurantoin buy phentermine without a prescription high blood pressure medicines stop hair loss viagra china use levitra female health coreg dosage carisoprodol price pain relief product breast enlargement depression pills buy how to treat flu home neck pain relief order imitrex online vitamin b-6 cialis soft tabs pharmacy software description of soma buy isoniazid cheap prevacid help ear infections on dog fat burning stop smoking remedies rhinitis treatment chronic pain relief birth control online meds without prescriptions buy lovastatin drug stores penis enlargement without pill cancer medicine buy deltasone cure for throat infection thyroid dogs dosage cipro viagra from uk cheap alcoholism treatment natural cure for constipation paxil cialis 5mg tablets amitriptyline uses topamax drugs lower heart rate drug discount codes dog medicines body fat loss joint pain recurring urinary tract infections ativan information buy drugs online cheap fast valium body building ambien maximum dosage information on valium how to sperm more chlamydia medication dosage buy cialis online viagra chest pain heart fluconazole interaction calcium channel blocker side effects zolpidem dosage online drug stores zelnorm muscle strength fluconazole buy stress gum free weight loss products information on gout low immune system online viagra cialis 20 buy cefixime phentermine from canada gain muscle mass fast lasix side effects buy singulair penis enlargement free natural muscle and joint health viagra online overnight cialis online aceon allergies and asthma diamox side effects weight loss software generic compazine price for tramadol high blood pressure symtoms osteoporosis help treatment severe constipation drug new smoking stop pain relief product xanax online dog health info clonazepam .5mg buy tribulus pregnancy prevention methods allergy hives