Cocos2d framework development tutorial for iPhone game development

Source: Internet
Author: User

IPhone gamesDevelopment and UseCocos2d frameworkThe development tutorial is what we will introduce in this article. Mobile devices are changing the relationship between our work and interaction with others. A new revolution is happening on us. People begin to consume more data through mobile devices.IPhoneApp stores have become the epitome of mobile app success and popularity, with games among the hottest categories. In this article, I will show you how to useCocos2d frameworkTo makeIPhone games.

Iphone games

Cocos2d framework

Cocos2dYes for BuildingIPhone gamesIs based onIPhoneBuilt on the core SDK to provide accelerationIPhone gamesDeveloped easy-to-use APIs.

Download and install the Cocos2d framework and template

To use the powerful functions of the Cocos2d framework, the first step is to download and install frameworks and templates related to the framework. Game State note: the original article provides the framework and template .)

Understand the basics of the framework

Before creating the first iPhone game, we recommend that you familiarize yourself with the basics of the Cocos2d framework, including the following four items:

Scenario. The scenario is special. It is the basis of all nodes. The purpose of the scenario is to present the operational parts of the game and display the game scenarios. Note: such as the game end, home page, and high score rankings ).

Level. The hierarchy shows the specific area of the game. The layers in Cocos2d are similar to those in Photoshop. This means that a scenario can be composed of multiple layers. One layer carries the background image, and the other layer is the beginning of the game action.

Interface. The interface refers to the things that give the game soul. For example, if you make a space game, your spacecraft and enemies are interfaces. Each role used to deepen the user's gaming experience can be regarded as an interface.

Create the first Cocos2d Project

Open Xcode and create a new project. 1. Select the Cocos2d project from the Project template menu.


 
Figure 1: Cocos2d template for Xcode

Click "select" to enter the next scenario. Enter MyFirstCocos2dProject as the project name and click "save ". Then, the system creates a Cocos2d project using the default template. This article describes the Cocos2d Framework Version 0.99. The default search is SDK 4.0. If you have installed the latest SDK, you will receive the "Basic SDK loss" message shown in 2.


 
Figure 2: Cocos2d project template base SDK missing

All you have to do is tell Cocos2d that we are using an updated SDK. To achieve this goal, click "Edit Project Settings" under the "project" tab, and specify the SDK version as shown in 3.

Figure 3: Selecting the installed SDK for iOS device

As you can see from the screenshot above, iOS SDK 4.0 is lost, but we can choose iOS SDK 4.1. After selecting the correct SDK, use "command B" to build the entire project. Project errors are not allowed. After achieving the above objectives, you can run the application using "command R. Figure 4 shows the pattern of the iPhone simulator in which the application is running.


 
Figure 4: The default Cocos2d project template output

The Cocos2d template has a basic execution program to display the "Hello World" Statement on the screen. FPS measurements are displayed at the bottom left of the screen. Note: in figure 4, 60.0 is displayed ). The default template is used to verify that the developer has correctly installed the framework and all components related to the framework. In the next section, we will continue to explore the Cocos2d framework.

Getting started with the Cocos2d framework

By default, the Cocos2d template is set to horizontal mode. The following code can be easily changed in the myfirstcocos2dprojecpdelegate. m file:

 
 
  1. [director setDeviceOrientation:kCCDeviceOrientationPortrait]; 

Now, if you run the application, you will find that the display is vertical rather than horizontal. Next, we need to change the background of the game. We have added the background3.png file to the project destination resource folder. The resource folder stores the resources used in all applications. Note: files, sound files, etc ). The following code sets the background image in the static mode:

 
 
  1. +(id) scene  
  2. {  
  3. // ‘scene’ is an autorelease object.  
  4. CCScene *scene = [CCScene node];  
  5.  
  6. // ‘layer’ is an autorelease object.  
  7. HelloWorld *layer = [HelloWorld node];  
  8.  
  9. CCSprite *background = [CCSprite spriteWithFile:@"Background3.png"];  
  10.  
  11. [layer addChild:background];  
  12.  
  13. // add layer as a child to scene  
  14. [scene addChild: layer];  
  15.  
  16. // return the scene  
  17. return scene;  

The CCSprite type contains the spriteWithFile method. The input file name is used as the parameter. Add the background interface to the hierarchy in addChild mode to get the effect shown in Figure 5.

Figure 5: Background sprite not positioned correctly

Unfortunately, the location of the background interface is incorrect. We need to set the anchor for the interface, as shown in figure 6.


 
Figure 6: Background sprite positioned correctly

The background image is suitable for screens of sizes of 320x480. If you want to make the device rotate, you need a background image suitable for the 480x320 Horizontal mode. In the next section, we will add an interface for the application.

Add Interface

Adding a background is only the beginning of application design. We need to add an operational interface for the game. We will use a smiley face image as our activity interface. Use the following code to add an interface for an application:

 
 
  1. // on “init” you need to initialize your instance  
  2. -(id) init  
  3. {  
  4. // always call “super” init  
  5. // Apple recommends to re-assign “self” with the “super” return value  
  6. if( (self=[super init] )) {  
  7.  
  8. // adding the sprite  
  9. CCSprite *smiley = [CCSprite spriteWithFile:@"smiley.png"];  
  10. smiley.position = ccp(100,100);  
  11. [self addChild:smiley];  
  12.  
  13. }  
  14. return self;  

Using the initial method, we created a CCSprite instance to present a smiley role. First place the smiling face in the appropriate position 100,100), and then add it to the layer. If you run the application, you will find the smiling face invisible. The reason is that the smiling face is located behind the background layer. To see the smiling face, we set the z axis value of the background interface to-1 and place the background interface after the smiling face interface. The Code is as follows: [layer addChild: background z:-1];

Figure 7 shows the adjusted result.

Figure 7: Smiley face sprite added to the game scene

In the above example, we use a hard code value when placing a smiley face on the screen. The following uses hard code values to place elements on the screen because the application will be based on the iPhone coordination system.

If you run an application on the iPad, you will find that the background and interface location are incorrect. To make the app display the same effect on iPhone and iPad devices, we must use the CGSize category to deepen the width and height values of the current device. The following code shows how to use CGSize:

 
 
  1. // on “init” you need to initialize your instance  
  2. -(id) init  
  3. {  
  4. // always call “super” init  
  5. // Apple recommends to re-assign “self” with the “super” return value  
  6. if( (self=[super init] )) {  
  7.  
  8. CGSize windowSize = [[CCDirector sharedDirector] winSize];  
  9.  
  10. // adding the sprite  
  11. CCSprite *smiley = [CCSprite spriteWithFile:@"smiley.png"];  
  12. smiley.position = ccp(windowSize.width/2,windowSize.height/2);  
  13. [self addChild:smiley];  
  14.  
  15. }  
  16.  
  17. return self;  

In the above Code, we use CCDirector to restore the winSize instance. WinSize refers to the size of the currently running iOS device. This ensures that the application runs correctly on the device.

Now, our smiling faces have not moved any more. In the next section, we will introduce how to move smiling faces on the screen.

Action and order

Cocos2d uses actions to add effects to interfaces or other objects in the CCNode object. The Cocos2d framework has many built-in actions, including CCFadeTo, CCMoveTo, and CCScaleBy. The following code uses the CCMoveTo action to move a smiling face to a specific position on the screen:

 
 
  1. // on “init” you need to initialize your instance  
  2. -(id) init  
  3. {  
  4. // always call “super” init  
  5. // Apple recommends to re-assign “self” with the “super” return value  
  6. if( (self=[super init] )) {  
  7.  
  8. CGSize windowSize = [[CCDirector sharedDirector] winSize];  
  9.  
  10. // adding the sprite  
  11. CCSprite *smiley = [CCSprite spriteWithFile:@"smiley.png"];  
  12. smiley.position = ccp(windowSize.width/2,windowSize.height/2);  
  13. [self addChild:smiley];  
  14.  
  15. // actions  
  16.  
  17. [smiley runAction:[CCMoveTo actionWithDuration:0.9 position:ccp(300,300)]];  
  18.  
  19. }  
  20.  
  21. return self;  

In this Code, we use the runAction method to execute the CCMoveTo action on the smiling face interface. The CCMoveTo action method uses actionWithDuration and location parameters. ActionWithDuration is the time required to complete the action. The location parameter refers to the location where the interface is moved. If you run the application, you will find the smiling face moving from the original position to the new position.

When you need to execute many actions on the interface, the plot is generated. For these scenarios, you can use the CCSpawn type to make sure that these actions are performed simultaneously on the interface. The following code is the application of CCSpawn in action:

 
 
  1. id moveAction = [CCMoveTo actionWithDuration:0.9 position:ccp(200,200)];  
  2. id fadeOutAction = [CCFadeOut actionWithDuration:0.9];  
  3. id callback = [CCCallFunc actionWithTarget:self selector:@selector(finishedAnimation)];  
  4.  
  5. [smiley runAction:[CCSequence actions:moveAction,fadeOutAction,callback,nil]];  
  6.  
  7. -(void) finishedAnimation  
  8. {  
  9. NSLog(@”animation has been finished!”);  

In this code, you can create two independent actions, CCMoveTo and CCFadeOut. Both actions are submitted as parameters to the CCSpawn method, so that the smiling face CCSprite can move and fade out the screen at the same time.

When using CCActions, it is useful to find the animation end point. In this section, we can use the CCSequence category. CCSequence allows developers to perform different actions one after another, and then the recycling function will eventually show that the animation has been completed. The following code is CCSequence:

 
 
  1. -(void) finishedAnimation  
  2. {  
  3. int x = arc4random() % 320;  
  4. int y = arc4random() % 480;  
  5.  
  6. id moveAction = [CCMoveTo actionWithDuration:0.9 position:ccp(x,y)];  
  7. id callback = [CCCallFunc actionWithTarget:self selector:@selector(finishedAnimation)];  
  8.  
  9. [smiley runAction:[CCSequence actions:moveAction,callback,nil]];  

This Code uses the CCCallFunc category to create a recycle function. Once both CCMoveTo and CCFadeOut are completed, the recycle function is triggered. Run the application in the excluded mode. After the animation is completed, the completed log information animation is displayed on the screen.

We can use the recycle function to repeatedly repeat the animation and move the interface to any position on the screen. This can be achieved through the finishedAnimation function. The following is the code:

 
 
  1. -(void) finishedAnimation  
  2. {  
  3. int x = arc4random() % 320;  
  4. int y = arc4random() % 480;  
  5.  
  6. id moveAction = [CCMoveTo actionWithDuration:0.9 position:ccp(x,y)];  
  7. id callback = [CCCallFunc actionWithTarget:self selector:@selector(finishedAnimation)];  
  8.  
  9. [smiley runAction:[CCSequence actions:moveAction,callback,nil]];  

Note: The above code can easily become independent methods of a specific category, which reduces errors such as copying and pasting. To make this article more concise, I have copied the code.

The arc4random function can be used to randomly generate numbers from 0 to n-1. We use the iPhone screen size game state Note: 320x480 pixels) to limit this random number. The obtained coordinates are then transmitted to the location parameter of the CCMoveTo function. FinishedAnimation can also be used as a recycling method to repeatedly repeat the animation after it ends. When you run the application, you will find that the smiling face is constantly moving from a random location to another random location.

Use of Touch Screen

Our smiling face moves freely on the screen and there is no way to stop it. In this section, we will allow users to control smiling faces through contact events. There are many ways to handle touch events. To make the design simple, we use the CCTouchesBegin event, which is triggered when users touch the screen. Before using the CCTouchesBegin event, use the original method to ensure that the isTouchEnabled feature is set to "yes ":

 
 
  1. -(void) ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event  
  2. {  
  3.  
  4. UITouch *touch = [touches anyObject];  
  5. CGPoint location = [touch locationInView:[touch view]];  
  6. location = [[CCDirector sharedDirector] convertToGL:location];  

The above ccTouchesBegan method can obtain the coordinates of the user's contact screen. In the ccTouchesBegan event, we need to know whether the user is smiling. We can achieve this goal by using the useful old-fashioned bidaras principle. The following code shows how to detect whether a smiling face has been touched:

 
 
  1. -(void) ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event  
  2. {  
  3.  
  4. UITouch *touch = [touches anyObject];  
  5. CGPoint location = [touch locationInView:[touch view]];  
  6. location = [[CCDirector sharedDirector] convertToGL:location];  
  7.  
  8. float distance = pow(smiley.position.x – location.x, 2) + pow(smiley.position.y – location.y, 2);  
  9. distance = sqrt(distance);  
  10.  
  11. if(distance <= 50)  
  12. {  
  13. [smiley runAction:[CCScaleBy actionWithDuration:0.9 scale:2.0]];  
  14.  
  15. [self performSelector:@selector(removeSmileyFromLayer) withObject:nil afterDelay:1.2];  
  16.  
  17. }  

In the above code, we can set the shortest distance between the smiling face and the contact. If the distance is less than 50 pixels, the smiling face of the program has been touched by the user. Then we run the CCScaleBy action to increase the smiling face, and then remove it from the layer using the traditional removeSmileyFromLayer method.

Add CCParticles

Now, when you touch the smiling face, it will increase and then disappear. We can use the Cocos2d particle framework to make it better. The particle framework allows you to achieve remarkable results through hundreds of CCNode object animations. Coordinates and works with all objects to create special effects.

We will use the particle explode effect, which will create an explosive effect after the user clicks a smiling face. The following code shows how to add special effects to a game. We use the same smiling face in the explosion, which means that once the smiling face is clicked, it will produce a smaller smiling face.

 
 
  1. if(distance <= 50)  
  2. {  
  3. CCParticleExplosion *explosion = [[CCParticleExplosion alloc] init];  
  4. explosion.texture = [[CCTextureCache sharedTextureCache] addImage:@”smiley.png”];  
  5. [explosion setDuration:2];  
  6. [explosion setAutoRemoveOnFinish:YES];  
  7. explosion.position = self.smiley.position;  
  8. [self addChild:explosion];  
  9.  
  10. [self removeChild:self.smiley cleanup:YES];  
  11. self.smiley = nil;  

In the above Code, we have initialized the CCParticleExplosion effect, which is one of the many available CCParticles in the Cocos2d framework. The particle effect interval is set to 2 seconds, and the particle object is set to automatically remove.

The results are displayed in figure 8.

Figure 8: CCParticleExplosion effect in action

I have introduced you briefly in this article.Cocos2d frameworkTo help you get started with development.IPhone games. If you want to explore the iOS development environment, useCocos2dBuild a simpleGamesYou can gain some development experience.

Summary:IPhone gamesDevelopment and UseCocos2d frameworkI hope this article will help you with the development tutorial!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.