Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon

How-To Tutorials - iOS Programming

64 Articles
article-image-getting-started-cocos2d
Packt
28 Feb 2011
8 min read
Save for later

Getting Started With Cocos2d

Packt
28 Feb 2011
8 min read
  Cocos2d for iPhone 0.99 Beginner's Guide Make mind-blowing 2D games for iPhone with this fast, flexible, and easy-to-use framework! A cool guide to learning cocos2d with iPhone to get you into the iPhone game industry quickly Learn all the aspects of cocos2d while building three different games Add a lot of trendy features such as particles and tilemaps to your games to captivate your players Full of illustrations, diagrams, and tips for building iPhone games, with clear step-by-step instructions and practical examples         Read more about this book       (For more resources on this subject, see here.) Downloading Cocos2d for iPhone Visit http://www.cocos2d-iphone.org for downloading the latest files. Search the downloads page, and there you will find the different versions available. As of this writing, Version 0.99.5 is the latest stable version. Once you have downloaded the file to your computer, uncompress the folder to your desktop, and rename it to Cocos2d. Open the uncompressed folder and take a look at its contents. Inside that folder, you will find everything you will need to make a game with Cocos2d. The following is a list of the important folders and files: Cocos2d: The bread and butter of Cocos2d. CocosDenshion: The sound engine that comes along. Cocoslive: Cocos2d comes packed with its own highscore server. You can easily set it up to create a scoreboard and ranking for your game. External: Here are the sources for Box2d and Chipmunk physics engines among other things. Extras: Useful classes created by the community. Resources: Images, sounds, tilemaps, and so on, used in the tests. Templates: The contents of the templates we'll soon install. Test: The samples used to demonstrate all the things Cocos2d can do. Tools: Some tools you may find useful, such as a ParticleView project that lets you preview how particles will look. License files: They are here in case you need to look at them. We'll start by taking a look at the samples. Time for action – opening the samples project Inside the cocos2d-iphone folder, you will find a file named cocos2d-iphone. xcodeproj. This project contains all the samples and named tests that come with the source code. Let's run one of them. Open the .xcodeproj file: In the groups and files panel you will find the source code of all the samples. There are more than 35 samples that cover all of the capabilities of Cocos2d, as shown in the following screenshot: Compile and run the SpriteTest: This project comes with a target for each of the available tests, so in order to try any of them you have to select them from the overview dropdown. Go ahead and select the SpriteTest target and click on Build and Run. If everything goes well the test should start running. Play a little with it, feel how it behaves, and be amazed by the endless possibilities.   What just happened?   You have just run your first Cocos2d application. If you want to run another sample, just select it by changing the "Active target". When you do so, the "active executable" should match to the same; if it doesn't select it manually by selecting it from the overview dropdown box. You can see which "active target" and "active executable" is selected from that overview dropdown box, they should be selected. Installing the templates Cocos2d comes with three templates. These templates are the starting point for any Cocos2d game. They let you: Create a simple Cocos2d project Create a Cocos2d project with Chipmunk as physics engine Create a Cocos2d project with Box2d as physics engine Which one you decide to use for your project depends on your needs. Right now we'll create a simple project from the first template. Time for action – installing the templates Carry out the following steps for installing the templates: Open the terminal. It is located in Applications Utilities | Terminal|. Assuming that you have uncompressed the folder on your desktop and renamed it as Cocos2d, type the following: cd desktop/Cocos2d ./install_template.sh You will see a lot of output in the terminal (as shown in the following screenshot); read it to check if the templates were installed successfully. If you are getting errors, check if you have downloaded the files correctly and uncompressed them into the desktop. If it is in another place you may get errors. We just installed the Xcode templates for Cocos2d. Now, each time you create a new project in Xcode, you will be given the choice of doing it by using a Cocos2d application. We'll see how to do that in a moment. Each time a new version of Cocos2d is released, there is a template file for that version. So, you should remember to install them each time. If you have a lot of older templates and you want to remove them, you can do so by going to Developer/Platforms/iPhoneOS. platform/Developer/Library/Xcode/Project Templates/Application and deleting the respective folder.   What just happened?   Templates are very useful and they are a great starting point for any new project. Having these templates available makes starting a new project an easy task. You will have all the Cocos2d sources arranged in groups, your AppDelegate already configured to make use of the framework and even a simple starting Layer. Creating a new project from the templates Now that you have the templates ready to use, it is time to make your first project. Time for action – creating a HelloCocos2d project We are going to create a new project named HelloCocos2d from the templates you have just installed. This won't be anything like a game, but just an introduction on how to get started. The steps are as follows: Open Xcode and select File New project| (Shift + cmd + N). 2. Cocos2d templates will appear right there along with the other Xcode project templates, as shown in the following screenshot: Select Cocos2d-0.99.1 Application. Name the project HelloCocos2d and save it to your Documents folder. Once you perform the preceding steps, the project you just created should open up. Let's take a look at the important folders that were generated: Cocos2d Sources: This is where the Cocos2d source code resides. Generally, you won't touch anything from here unless you want to make modifications to the framework or want to know how it works. Classes: This is where the classes you create will reside. As you may see, two classes were automatically created, thanks to the template. We'll explore them in a moment. Resources: This is where you will include all the assets needed for your game. Go ahead and run the application. Click on Build and go and congratulate yourself, as you have created your first Cocos2d project. Let's stop for a moment and take a look at what was created here. When you run the application you'll notice a couple of things, as follows: The Cocos2d for iPhone logo shows up as soon as the application starts. Then a CCLabel is created with the text Hello World. You can see some numbers in the lower-left corner of the screen. That is the current FPS the game is running at. In a moment, we'll see how this is achieved by taking a look at the generated classes.   What just happened?   We have just created our first project from one of the templates that we installed before. As you can see, using those templates makes starting a Cocos2d project quite easy and lets you get your hands on the actual game's code sooner. Managing the game with the CCDirector The CCDirector is the class whose main purpose is scene management. It is responsible for switching scenes, setting the desired FPS, the device orientation, and a lot of other things. The CCDirector is the class responsible for initializing OpenGL ES. If you grab an older Cocos2d project you might notice that all Cocos2d classes have the "CC" prefix missing. Those were added recently to avoid naming problems. Objective-c doesn't have the concept of namespaces, so if Apple at some point decided to create a Director class, those would collide. Types of CCDirectors There are currently four types of directors; for most applications, you will want to use the default one: NSTimer Director: It triggers the main loop from an NSTimer object. It is the slowest of the Directors, but it integrates well with UIKit objects. You can also customize the update interval from 1 to 60. Mainloop Director: It triggers the main loop from a custom main loop. It is faster than the NSTimer Director, but it does not integrate well with UIKit objects, and its interval update can't be customized. ThreadMainLoop Director: It has the same advantages and limitations as the Mainloop Director. When using this type of Director, the main loop is triggered from a thread, but it will be executed on the main thread. DisplayLink Director: This type of Director is only available in OS 3.1+. This is the one used by default. It is faster than the NSTimer Director and integrates well with UIKit objects. The interval update can be set to 1/60, 1/30, or 1/15. Those are the available Directors, most of the times you will not need to make any changes here.
Read more
  • 0
  • 0
  • 1795

article-image-cocos2d-iphone-handling-accelerometer-input-and-detecting-collisions
Packt
30 Dec 2010
4 min read
Save for later

Cocos2d for iPhone: Handling Accelerometer Input and Detecting Collisions

Packt
30 Dec 2010
4 min read
  Cocos2d for iPhone 0.99 Beginner's Guide Make mind-blowing 2D games for iPhone with this fast, flexible, and easy-to-use framework! A cool guide to learning cocos2d with iPhone to get you into the iPhone game industry quickly Learn all the aspects of cocos2d while building three different games Add a lot of trendy features such as particles and tilemaps to your games to captivate your players Full of illustrations, diagrams, and tips for building iPhone games, with clear step-by-step instructions and practical examples         Read more about this book       (For more resources on Cocos2d, see here.) Handling accelerometer input Now that we have our three basic elements roughly defined, let's focus on the player's interaction with the hero. We will start by allowing the player to move the hero using the device's built-in accelerometer. The accelerometer opens a new world of interaction between the user and the device, allowing for a lot of interesting uses. There are already lots of applications and games that use this feature in innovative ways. For example, in the game Rolando, players have to roll the main character around using the accelerometer, and here we will be doing something similar to that. The accelerometer gives you data of the current tilting of the device in the three axes, that is the x, y, and z axes. Depending on the game you are making, you will be needing all that data or just the values for one or two of the axis. Fortunately, Apple has made it very easy for developers to access the data provided by the accelerometer hardware. Time for action – moving your hero with the accelerometer We have to add a few lines of code in order to have our hero move. The end result will be the hero moving horizontally when the user tilts the device to the left or to the right. We will also do some checkovers, in order to avoid the hero moving out of the screen. The first step involved in using the accelerometer is to enable it for the CCLayers that want to receive its input. Add the following line of code to the GameLayer's init method: self.isAccelerometerEnabled = YES; Then we have to set the update interval for the accelerometer. This will set the interval at which the hardware delivers the data to the GameLayer. Add the following line afterwards: [[UIAccelerometer sharedAccelerometer] setUpdateInterval:(1.0 / 60)]; Now that our GameLayer is prepared to receive accelerometer input, we just have to implement the method that receives and handles it. The following is the method that receives the input and makes our hero move. Add it to the GameLayer class: - (void)accelerometer:(UIAccelerometer*)accelerometer didAccelerate:(UIAcceleration*)acceleration{ static float prevX=0, prevY=0; #define kFilterFactor 0.05f float accelX = (float) acceleration.x * kFilterFactor + (1- kFilterFactor)*prevX; prevX = accelX;//If the hero object exists, we use the calculated accelerometer values to move him if(hero) {//We calculate the speed it will have and constrain it so it doesn't move faster than he is allowed to float speed = -20 * -accelX; if(speed > hero.movementSpeed) speed = hero.movementSpeed; else if(speed < -hero.movementSpeed) speed = -hero.movementSpeed;//We also check that the hero won't go past the borders of the screen, if he would exit the screen we don't move it if((accelX >0 || hero.mySprite.position.x >hero.mySprite.textureRect.size.width / 2) && ( accelX <0 ||hero.mySprite.position.x <320- hero.mySprite.textureRect.size.width / 2)) [hero.mySprite setPosition:ccp(hero.mySprite.position.x +speed,hero.mySprite.position.y)]; }} Run the game now. You should be able to move the hero by tilting you device, as shown in the following screenshot: The iPhone simulator does not provide a way to simulate accelerometer input, so you won't be able to test it in there; it won't move at all. What just happened? Accelerometer input can be achieved quite easily and fast. In our example, we just used the x component of the accelerometer input to handle the hero's position. The accelX variable holds the current value of the x component. This value ranges from -1 to 1, so we multiply it by the speed of the hero, then we just add that result to the current position of the hero, giving the sense of motion. We are also checking to make sure that the hero is not going off the screen before applying that movement.
Read more
  • 0
  • 0
  • 2065

article-image-cocos2d-iphone-adding-layers-and-making-simple-pause-screen
Packt
30 Dec 2010
6 min read
Save for later

Cocos2d for iPhone: Adding Layers and Making a Simple Pause Screen

Packt
30 Dec 2010
6 min read
Adding more layers to scenes As we have discussed before, a scene can contain any number of layers you want. Well, as long as performance is not an issue. As CCLayer inherits from CCNode, it can be added as the child of CCScenes or other CCLayers, allowing you to organize your content in a nice fashion. There are three types of CCLayers that you can use and combine in your games. They are as follows: CCLayer: We have been using them forever. Besides all the features inherited from CCNodes, they can receive touches and accelerometer input. CCColorLayer: They inherit from CCLayer so besides being able to receive touches and accelerometer input, their opacity and RGB colors can be changed. CCMultiplexLayer: It inherits from CCLayer and can have many children, but only one will be active at any given time. You can switch between those children. In the following examples, we will be creating some CCLayers in different ways to achieve different results. Time for action – creating a HUD to display lives and the score We will begin by building a simple Heads Up Display (HUD) for our game. Its purpose is to show some useful data about the current state of the game to the player. The idea behind making the HUD into a new layer is to simplify the logic of the GameLayer. This way, the GameLayer will only handle stuff of the game itself while leaving the HUD logic to the HUDLayer. In our game, the HUD will display the remaining lives, score, remaining bombs, and anything you want to display later. Once it is done, all we need to do in the GameLayer is send a message so the HUDLayer gets updated. The first step in creating the HUD is to add a new file to the project. In the Xcode project, select File | New file and add a new Objective-C class. Rename it as HUDLayer. Replace the contents of the HudLayer.h with the following lines: #import <Foundation/Foundation.h> #import "cocos2d.h" #import "GameScene.h" @interface HudLayer : CCLayer { CCBitmapFontAtlas * level; CCBitmapFontAtlas * score; CCBitmapFontAtlas * bombs; NSMutableArray * lives; } @property (nonatomic,retain) CCBitmapFontAtlas * level; @property (nonatomic,retain) CCBitmapFontAtlas * score; @property (nonatomic,retain) CCBitmapFontAtlas * bombs; @property (nonatomic,retain) NSMutableArray * lives; @end Do the same with the contents of the HudLayer.m file: #import "HudLayer.h" @implementation HudLayer @synthesize lives,bombs,score,level; - (id) init { if ((self = [super init])) { CCSprite * background = [CCSprite spriteWithFile:@"hud_background.png"]; [background setPosition:ccp(160,455)]; [self addChild:background]; lives = [[NSMutableArray arrayWithCapacity:3]retain]; for(int i=0;i<3;i++) { CCSprite * life = [CCSprite spriteWithFile:@"hud_life.png"]; [life setPosition:ccp(18+ 28*i,465)]; [self addChild:life]; [lives addObject:life]; } CCSprite * bomb = [CCSprite spriteWithFile:@"hud_bomb.png"]; [bomb setPosition:ccp(18,445)]; [self addChild:bomb]; GameLayer * gl = (GameLayer *)[self.parent getChildByTag:KGameLayer]; level = [CCBitmapFontAtlas bitmapFontAtlasWithString:@"Level 1" fntFile:@"hud_font.fnt"]; [level setAnchorPoint:ccp(1,0.5)]; [level setPosition:ccp(310,465)]; [level setColor:ccBLACK]; [self addChild:level]; score = [CCBitmapFontAtlas bitmapFontAtlasWithString:@"Score 0" fntFile:@"hud_font.fnt"]; [score setAnchorPoint:ccp(1,0.5)]; [score setPosition:ccp(310,445)]; [score setColor:ccBLACK]; [self addChild:score]; bombs = [CCBitmapFontAtlas bitmapFontAtlasWithString:@"X3" fntFile:@"hud_font.fnt"]; [bombs setAnchorPoint:ccp(1,0.5)]; [bombs setPosition:ccp(47,440)]; [bombs setColor:ccBLACK]; [self addChild:bombs]; } return self; } - (void) dealloc { [super dealloc]; [lives release]; } @end You can find the images and the font used above in the companion files at Support. What we have to do now is load this new layer and add it as a child of the GameScene. Change the init method of the GameScene class to look like the following: - (id) init { self = [super init]; if (self != nil) { [self addChild:[GameLayer node] z:0 tag:KGameLayer]; //kGameLayer defined in the GameScene.h file. #define kGameLayer 1 [self addChild:[HudLayer node] z:1 tag:KHudLayer]; //kHudLayer defined in the GameScene.h file. #define kHudLayer 2 } return self; } The only thing missing now is to make some changes here and there to be able to update the HUDLayer with the actual state of the game. Let's update the score and remaining lives, for now. Change the loseLife method of the GameLayer class: -(void)loseLife { self.lives--; HudLayer * hl = (HudLayer *)[self.parent getChildByTag:KHudLayer]; CCSprite * live = [hl.lives objectAtIndex:self.lives]; [live setVisible:NO]; if(self.lives ==0) { [self resetGame]; //LOSE THE GAME //GO TO GAME OVER LAYER } } Add the resetGame method: -(void)resetGame { HudLayer * hl = (HudLayer *)[self.parent getChildByTag:KHudLayer]; for(CCSprite * c in hl.lives) { [c setVisible:YES]; } self.level=1; [hl.level setString:@"Level 1"]; self.score=0; [hl.score setString:@"Score 0"]; self.bombs =3; [hl.bombs setString:@"X3"]; lives = STARTING_LIVES; } These methods will handle the displaying of the remaining lives. Finally, modify the Enemy class's destroy method, so it updates the score label instead of logging the score to the console: -(void)destroy { [self reset]; [theGame setScore:theGame.score+100]; HudLayer * hl = (HudLayer *)[theGame.parent getChildByTag:KHudLayer]; [hl.score setString:[NSString stringWithFormat:@"Score %d",theGame.score]]; } Run the game. You should see a HUD at the top of the screen (as shown in the following screenshot) with all the actual information about the state of the game. Destroy some enemies to see the score updated and lose some lives to see the "lives" icons disappear. What just happened? We just went through the steps needed to create a new layer, adding it to the scene and updating its contents. Our new layer just holds some information of the game state and displays it to the player. In order to achieve that we just added a few CCSprites and CCBitmapFontAtlases which get updated when needed. Once the HudLayer class was created we added it to the GameScene over the GameLayer, so its contents are always shown on top of the GameLayer's ones. We also provided a tag for both layers, as we will need to access them from other places. We could also have added a reference to the other layer inside them. That is all what we need to do in order to add more layers to a scene. The rest of the code just handles the updating of the contents of the HudLayer. When the player hits an enemy, a score is awarded. Then the label placed in the HUD is updated. When the hero is hit and a life is lost, we just turn the corresponding icon's visibility off, then when the game is reset we turn all of them on.
Read more
  • 0
  • 0
  • 2582
Banner background image

article-image-cocos2d-iphone-surfing-through-scenes
Packt
29 Dec 2010
10 min read
Save for later

Cocos2d for iPhone: Surfing Through Scenes

Packt
29 Dec 2010
10 min read
  Cocos2d for iPhone 0.99 Beginner's Guide Make mind-blowing 2D games for iPhone with this fast, flexible, and easy-to-use framework! A cool guide to learning cocos2d with iPhone to get you into the iPhone game industry quickly Learn all the aspects of cocos2d while building three different games Add a lot of trendy features such as particles and tilemaps to your games to captivate your players Full of illustrations, diagrams, and tips for building iPhone games, with clear step-by-step instructions and practical examples         Read more about this book       (For more resources on Cocos2d, see here.) We'll be doing a lot of things in this article, so let's get started. Aerial Gun, a vertical shooter game Let's talk about the game we will be making. Aerial Gun, as I said earlier, is a vertical shooter game. That means you will be in control of an airship which will move vertically. Actually, the airship won't be moving anywhere (well except to the left and right); what is really going to move here is the background, giving the sense the airship is the one moving. The player will be able to control the airship by using accelerometer controls. We'll also provide some areas where the player can touch to fire bullets or bombs to destroy the enemies. Enemies will be appearing at different time intervals and will have some different behaviors attached to them. For example, some of them could just move towards the airship, others may stay there and shoot back, and so on. We'll do it in a way you can create more custom behaviors later. For this game we will be using the Cocos2d template again, just because it is the easier way to have a project properly set up, at least to begin our work. So, follow the same steps as when we created the Coloured Stones game. Just open Xcode and go to the File menu, select to create a new project. Then choose the Cocos2d template (the simple one, without any physics engine) and give a name to the project. I will call it AerialGun. Once you do that, your new project should be opened. Creating new scenes We will begin this new game by first doing a couple of scenes other than the one that holds the actual game. If you take a look at the class that the template generates, at first sight you won't find what would appear to be a scene. That is because the template handles that in a confusing fashion, at least for people who are just getting started with Cocos2d. Let's take a look at that. Open the newly generated HelloWorldScene.m file. This is the same code in which we based our first game. This time we will analyze it so you understand what it is doing behind scenes. Take a look at the first method of the implementation of the HelloWorld Layer: +(id) scene{ // 'scene' is an autorelease object. CCScene *scene = [CCScene node]; // 'layer' is an autorelease object. HelloWorld *layer = [HelloWorld node]; // add layer as a child to scene [scene addChild: layer]; // return the scene return scene;} If you remember well, this is the method that get's called in the AppDelegate when the Director needs to start running with a scene. So why are we passing the method of a layer instead of an instance of a CCScene class? If you pay attention to the +(id)scene method of the layer, what it does is to instantiate a CCScene object, then it instantiates a HelloWorld object (the layer), and then it adds that layer to the scene and returns it. This actually works as you have witnessed and is pretty quick to set up, and get you up and running. However, sometimes you will need to have you own custom scenes, that is a class that inherits from CCScene and extends it in some fashion. Now we are going to create some of the scenes that we need for this game and add a layer to each one. Then when it is time to work with the game scene we will modify it to match our needs. Before doing anything, please change the name of the HelloWorldlayer to GameLayer and the name of the HelloWorldScene to GameScene, just as we did back then with our first game. Time for action – creating the splash and main menu scene We will begin with a simple scene, the splash screen. A splash screen is the first thing that appears as you launch a game. Well, the second if you count the Default.png image. The objective of this screen is to show the player some information about the developer, other companies that helped, and so on. Most times you will just show a couple and logos and move to the main menu. So, what we will do now is put a new Default.png image, then create the SplashScene. The Default.png image is located in your project's Resources group folder and it is the first image that is shown when the application is launched. You should always have one, so that something is shown while the application is being launched. This happens before anything is initialized, so you can't do anything else other than show this image. Its dimensions must be 320 * 480 (when developing for older generation iPhones), so if your game is supposed to be in landscape mode, you should rotate the image with any graphics software before including it in your project. The SplashScene is going to show a sprite for a moment, then fade it, show another one and then move to the GameScene. Let's add a new file to the project. Select New File (CMD + N) from the File menu, then select Objective-C class (we are going to do it from scratch anyways) and name it SplashScene. This file will hold both the SplashScene and the SplashLayer classes. The SplashLayer will be added as a child of the SplashScene, and inside the layer we will add the sprites. Before writing any code, add to the project the three splash images I created for you. You can find them in the companion files folder. Once you have them added into your project we can begin working on the SplashScene. The following is the SplashScene.h: #import <Foundation/Foundation.h>#import "cocos2d.h"#import "MainMenuScene.h"@interface SplashScene : CCScene { }@end@interface SplashLayer : CCLayer { }@end And the SplashScene.m file: #import "SplashScene.h" //Here is the implementation of the SplashScene@implementation SplashScene- (id) init{ self = [super init]; if (self != nil) { [self addChild:[SplashLayer node]]; } return self;}-(void)dealloc{ [super dealloc];}@end//And here is the implementation of the SplashLayer@implementation SplashLayer- (id) init{ if ((self = [super init])) { isTouchEnabled = YES; NSMutableArray * splashImages = [[NSMutableArray alloc]init]; for(int i =1;i<=3;i++) { CCSprite * splashImage = [CCSprite spriteWithFile:[NSString stringWithFormat:@"splash%d.png",i]]; [splashImage setPosition:ccp(240,160)]; [self addChild:splashImage]; if(i!=1) [splashImage setOpacity:0]; [splashImages addObject:splashImage]; } [self fadeAndShow:splashImages]; } return self;}//Now we add the methods that handle the image switching-(void)fadeAndShow:(NSMutableArray *)images{ if([images count]<=1) { [images release]; [[CCDirector sharedDirector]replaceScene:[MainMenuScene node]]; } else { CCSprite * actual = (CCSprite *)[images objectAtIndex:0]; [images removeObjectAtIndex:0]; CCSprite * next = (CCSprite *)[images objectAtIndex:0]; [actual runAction:[CCSequence actions:[CCDelayTime actionWithDuration:2], [CCFadeOut actionWithDuration:1],[CCCallFuncN actionWithTarget:self selector:@selector(remove:)],nil]]; [next runAction:[CCSequence actions:[CCDelayTime actionWithDuration:2], [CCFadeIn actionWithDuration:1],[CCDelayTime actionWithDuration:2], [CCCallFuncND actionWithTarget:self selector:@selector(cFadeAndShow: data:) data:images],nil]]; } }-(void) cFadeAndShow:(id)sender data:(void*)data{ NSMutableArray * images = (NSMutableArray *)data; [self fadeAndShow:images];}-(void)remove:(CCSprite *)s{ [s.parent removeChild:s cleanup:YES];}-(void)dealloc{ [super dealloc];}@end As you may notice, I have put together two classes in only one file. You can do this with any number of classes, as long you don't get lost in such a long file. Generally, you will create a pair of files (the .m and .h) for each class, but as the SplashScene class has very little code, I'd rather put it there. For this to work properly, we need to make some other changes. First, open the AerialGunAppDelegate.m file and change the line where the the Director starts running the GameScene. We want it to start by running the SplashScene now. So replace that line with the following: [[CCDirector sharedDirector] runWithScene:[SplashScene node]]; Also remember to import your SplashScene.h file in order for the project to properly compile. Finally, we have to create the MainMenuScene, which is the scene the Director will run after the last image has faded out. So, let's create that one and leave it blank for now. The following is the MainMenuScene.h file: #import <Foundation/Foundation.h>#import "cocos2d.h"@interface MainMenuScene : CCScene { }@end@interface MainMenuLayer : CCLayer { }@end The following is the MainMenuScene.m file: #import "MainMenuScene.h"@implementation MainMenuScene- (id) init{ self = [super init]; if (self != nil) { [self addChild:[MainMenuLayer node]]; } return self;}-(void)dealloc{ [super dealloc];}@end@implementation MainMenuLayer- (id) init{ if ((self = [super init])) { isTouchEnabled = YES; } return self;}-(void)dealloc{ [super dealloc];}@end That would be all for now. Run the project and you should see the first image appear. Then fade to the next one after a while and continue till the last one. Once the last one has faded out, we move on to the MainMenuScene. What just happened? Creating a new scene is as easy as that. You can see from the MainMenuScene code that what we are doing is quite simple; when the MainMenuScene gets created we just instantiate the MainMenuLayer and add it to the scene. That layer is where we will later add all the necessary logic for the main menu. The MainMenuScene as well as the SplashScene both inherit from the CCScene class. This class is just another CCNode. Let's take a little look at the logic behind the SplashScene: NSMutableArray * splashImages = [[NSMutableArray alloc]init];for(int i =1;i<=3;i++){ CCSprite * splashImage = [CCSprite spriteWithFile:[NSString stringWithFormat:@"splash%d.png",i]]; [splashImage setPosition:ccp(240,160)]; [self addChild:splashImage]; if(i!=1) [splashImage setOpacity:0]; [splashImages addObject:splashImage];} [self fadeAndShow:splashImages]; This piece of code is from the SplashLayer init method. What we are doing here is creating an array that will hold any amount of sprites (in this case, three of them). Then we create and add those sprites to it. Finally, the fadeAndShow method is called, passing that newly created array to it. The fadeAndShow method is responsible for fading the images it has. It grabs the first image in the array (after that, the sprite is removed from the array). It then grabs the next one. Then it applies actions to both of them to fade them in and out. The last action of the second sprite's action is a CCCallFuncND, which we use to call the fadeAndShow method again with the modified array. This occurs if there is more than one remaining sprite in the array. If there isn't, the fadeAndShow method calls the Director's replaceScene method with the MainMenuScene. I have made the SplashLayer logic, so you can add more splash images to the array (or leave just one) if you like. Generally, just one or two images will be more than enough.
Read more
  • 0
  • 0
  • 2887
Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at $19.99/month. Cancel anytime