Cocos2d-iphone Study Notes

Source: Internet
Author: User

This is according to me Zhiyi <Zhiyi Cocco2D-iPhone development tutorial> do some of the problem summary, hope to help everyone.

 

1. Let's talk about the iphone game startup process.

A:

(1) main program entry-main. m

 

Int main (int argc, char * argv []) {

NSAID utoreleasepool * pool = [[NSAID utoreleasepool alloc] init];

UIApplicationMain (argc, argv, nil, @ "T01AppDelegate ");

[Pool drain];

 

Return 0;

}

 

 

(2) The program control is passed to the application proxy object-the code is T01AppDelegate

The T01AppDelegate object processes various system events that need to be handled by the current application by implementing the application interface UIApplicationDelegate defined by the iphone OS system:

L give up control: applicationWillResignActive

L control: applicationDidBecomeActive

L memory alarm: applicationDidReceiveMemoryWarning

L program exit prompt: applicationWillTerminate

L system time change: applicationSignificantTimeChange

After Initialization is complete, the control of the program is passed to the class library of the Cocos2d-iphone through the applicationDidFinishLaunching function.

(3) When the Cocos2d-iphone receives control of the program, start preparing to start the game master screen preparation:

3.1 obtain the main window object (handle) and save it by window.

3.2 bind "director" of the Cocos2d-iphone

3.3 set basic attributes of the "director" Object

3.4 scenario created by directors

3.5 Add the Object layer to the current scenario

3.6 start and run the scenario by the Director object

 

2. How to install the cocos2d-iphone engine into xcode?

A: Start the terminal, locate the directory where the cocos2d-iphone is located, and then run the command...

/Install-templates.sh

 

However, if the installation fails, you must have higher permissions. The command is as follows:

----------------------------

Sudo-s press ENTER

Password: enter the password and press Enter.

----------------------------

Switch to bash-3.2 # user.

 

3. How does xcode4 set Active Target?

A: Click product-> edit schema.... A manage schemes… is displayed at the bottom of the pop-up page... Double-click the **. xcodeproj file you want to run.

 

4. Almost all components of game development?

A: Scene-layer genie director.

The complexity of these four elements determines the complexity of the game.

 

5. How does layer handle events?

A: I personally call it sinking. that is, the event is received from the top layer. If the event is not processed, it is sunk to the following layer, and so on, until a layer handles the event, the event does not sink.

 

6. For convenience, the Cocos2d-iphone provides some common layers from the technical implementation perspective, such as the menus used for processing menus (menus), The colorlayers for processing color display, etc.

 

7. What is the essence of the genie?

A: The genie is a constantly changing image.

 

8. What is a game?

A: A game is a game where one or more Ai-controlled genie interact with one or more system-controlled genie: close-to-human combat, remote shooting, close-to-conversation, and so on.

 

9. The role of the Director (Cocos2d-iphone )?

A: The Director switches between control scenarios according to the workflow.

Since the scenario is controlled, there are a series of Operation scenarios, such as termination, stack pressure, activation of the current scenario, and guidance for the next scenario.

Note: At the same time, only one Scene (scenario) is activated;

Scene is a Layer container.

 

10. Q: If the Director object is in an operation scenario, what attributes and methods are related to the scenario?

A:

Attribute:

(1) Scene * runningScene _;

(2) Scene * nextScene;

(3) NSMutableArray * sceneStack _;

Method:

(1) (void) runWithScene: (Scene *) scene; the main program starts and shows the method of the first scenario.

(2) (void) pushScene: (Scene *) scene; suspends the current Scene and presses the stack to the queue. Set the input scenario to the current execution scenario.

(3) (void) popscene; the last scenario in the execution queue. The current scenario is released. If no scenario exists in the queue, the system automatically exits and calls the end method.

(4) (void) replacescene: (SCENE *) scene; Replace the current scenario directly with one scenario, and the current scenario is released.

(5) (void) end; end the scenario;

 

 

11. What are the main functions of cclayer?

(1) receives touch input from the iPhone.

(2) accelerometer Input

 

12. In order to facilitate development, Cocos2d-iphone provides some direct available layer, respectively what?

Answer: 3.

Color Layer-Colorlayer: This is a transparent layer that can be filled with colors according to RGB settings. You can set the layer size through setcontentsize to change the color block size. It also supports action to flash and gradient.

Menu Layer-Menu: This is a collection class using menu objects. The menuitem class instances form menu management selection layers with various buttons.

Note: The instance in this layer must be a menuitem class or subclass instance.

The Menu class controls the horizontal display of MenuItem class instances, and displays MenuItem class instances in vertical or multi-row sorting.

Composite Layer-multiplexlayer

 

13. Can MenuItem be used directly? What is his main task?

A: MenuItem is a base class. Do not use it directly as the parent class of all menu items. MenuItem mainly performs the following two tasks:

(1) set the button status

(2) callback handler.

 

 

14. I found a common method in the subclass and implementation file of MenuItem.Parent class definitionAndSubclass DefinitionWrite it in a file, and then implement different sub-classes in different files. For example:

# Import <Foundation/Foundation. h>

/// Parent class ///

@ Interface Person

@ End

 

//// // Subclass 1

@ Interface Boy

@ End

 

 

/// // Sub-class 2

@ Interface Gril

@ End

 

 

----------------------------------

Implement the Boy class

# Import "Person. h"

@ Implementation Boy

@ End

 

Implement Girl class

# Import "Person. h"

@ Implementation Gril

@ End

 

 

15. What are the functions of Scene, layer, and sprite?

A:

Scene:

(1) as the total container object of a scenario, including all content objects (menus, statuses, game roles, and NPC) belong to this object. the cascade relationship is determined by the Z parameter of addChild of CocosNode.

(2) Special Effects of scenario switching. Because all the scenario switching effects are derived from the TransitionScene subclass of Scene. (remember to add CCScene before the class in the Cocos2d-iphone)

 

Layer-To handle input Problems

(1) Touch event processing

(2) Dynamic induction Processing

 

Sprite

(1) Displaying static images (such as background images)

(2) Use AtlasSprite to display game and NPC roles

 

16. How is the scenario converted?

A:

(1) First, a new scenario container

(2) Add the layer to be changed to the newly opened scene.

(3) Change layers with directors

For example:

-(Void) nextGame (id) sender

{

Scene * SC = [Scene node];

[SC addChild: [NextGameLayer node];

[[Director shareddire] replaceScene: SC];

}

If special effects such as gradient and slide are required during layer switching, they can be used to CCTransition and its subclass, for example:

[Director shareddire] replaceScene: [CCTransitionSlideInR transitionWithDuration: 1.2f scene: SC];

 

17. How many image libraries does the Iphone platform provide? Respectively?

A: There are two types: quartz 2D and OpenGL ES.

Quartz 2d is a subset of the Core Graphics drawing library.

OpenGL ES is a subset of cross-platform graphics library OpenGL. (This is used in Cocos2d-iphone)

What are their differences? Their coordinate system origins are different.

 

18. What is anchorPoint )?

A: anchorPoint is a point defined in the genie, layer, and so on. Place the genie layer and wait until it is a reference point in the coordinate system.

 

19. *. What format is fnt used?

A:. fnt is the font file set. It can be loaded to the system to generate the corresponding font. For example:

CCLabelBMFont * showFont = [CCLabelBMFont labelWithString: @ "hello world" fntFile: @ "font09.fnt"];

 

20. What are the roles of CCTextureCache and CCSpriteBatchNode and CCSpriteFrameCache?

A:

Cctexturecache

Through the system class CCTextureCache, The Cocos2d-iphone library, according to the file name as the primary key index all the image files read when running. When the file name is the same, directly return the memory image instead of reading the file.

All implementation related to image files centrally and transparently call single-instance objects of the CCTextureCache class at the underlying layer to ensure minimum system IO operations and improve program running efficiency.

Ccspritebatchnode

Batch painting is submitted to reduce the number of OpenGL function calls.

Through the ccspritesheet system class, the Cocos2d-iphone library submits OpenGL output for all the child ccsprite objects to which ccspritebatchnode class objects.

CCSpriteFrameCache

Manages the total number of frames of an animation effect. This class provides a simple image processing tool http://zwoptex.zwople.com/output file support. This class also uses cctexturecache.

 

21. In the Cocos2d-iphone, what is the way to call the callback function cyclically?

A: [self schedule: @ selector (step: interval: 1];

 

22. How to set an animation and run it?

A: Use ccanimation, for example:

Ccspritebatchnode * Mgr = [ccspritebatchnode batchnodewithfile: @”fight.png "capacity: 5];

 

Ccanimation * ans = [ccanimation animationwitharray: Nil delay: 0.2f];

[Ans addframewithtexture: Mgr. Texture rect: cgrectmake (0, 0, 31, 30)];

[Ans addframewithtexture: Mgr. Texture rect: cgrectmake (5, 0, 31, 30)];

[Ans addFrameWithTexture: mgr. texture rect: CGRectMake (10, 0, 31, 30)];

In this way, the ans object saves a set of animation frames.

How do I create an action based on an animation?

Fight = [CCSprite spriteWithTexture: mgr. texture rect: CGRectMake (0, 0, 31, 30)];

Id action = [CCAnimate actionWithAnimation: ans];

[Fight runAction: [CCRepeatForever actionWithAction: action];

 

 

23. What protocols does CCLayer comply with to facilitate users' touch operations? What is the Protocol definition method?

A: The CCLayer complies with the touch-related protocol.<CCStandardTouchDelegate>

 

@ Protocol CCStandardTouchDelegate <NSObject>

@ Optional

-(Void) ccTouchesBegan: (NSSet *) touches withEvent :( UIEvent *) event;

-(Void) ccTouchesMoved: (NSSet *) touches withEvent: (UIEvent *) event;

-(Void) ccTouchesEnded: (NSSet *) touches withEvent: (UIEvent *) event;

-(Void) ccTouchesCancelled: (NSSet *) touches withEvent: (UIEvent *) event;

@ End

 

24. The ccTouchXX method of the <CCStandardTouchDelegate> protocol is implemented. Why is the method not entered when the program is running?

A: To start a trigger event, you must first Add the following code to the layer initialization method:

Self. isTouchEnabled = YES; // The default value is NO.

 

 

 

25. How can I determine whether it is a contract for a gesture or a separate touch?

A:

(1) determine whether it is a dual-touch

(2) calculate the distance between two points

(3) In the moving method, determine the distance between two points and compare them with the distance between the previous two points.

 

The sample code is as follows:

 

-(Void) ccTouchesBegan :( NSSet *) touches withEvent :( UIEvent *) event {

NSSet * allTouches = [event allTouches];

Float distances;

Float afterMovedDistances;

Swith ([allTouches count]) {

Case 1: // Single Point

Break;

Case 2: // two points

UITouch * touchStartPoint = [[allTouches allObjects] objectAtIndex: 0];

UITouch * touchToPoint = [[allTouches allObjects] objectAtIndex: 1];

Distance = [self distanceBetweenTwoPoints :( UITouch *) start toPoint :( UITouch *) to];

Break;

Default:

Break;

}

}

 

 

-(Float) distanceBetweenTwoPoints :( UITouch *) start toPoint: (UITouch *) {

CGPoint startLocation = [start locationInView: [start view];

CGPoint toLocation = [[to locationInView: [to view];

Float x = startLocation. x-toLocation. x;

Float y = startLocation. y-toLocation. y;

Return sqrt (x * x + y * y); // calculates the length of a Cartesian triangle diagonal line.

}

-(Void) ccTouchesMoved: (NSSet *) touches withEvent: (UIEvent *) event {

NSSet * allTouches = [event allTouches];

Swich ([allTouches count]) {

Case 1: break;

Case 2:

UITouch * startTouch = [[allTouches allObjects] objectAtIndex: 0];

UITouch * toTouch = [[allTouches allObjects] objectAtIndex: 1];

AfterMovedDistances = [self distanceBetweenTwoPoints: startTouch toPoint: toTouch];

If (distances> afterMovedDistances ){

// Combine gesture

} Else if (distances <afterMovedDistances ){

// Separate gesture

}

Break;

 

Default:

Break;

}

}

 

 

26. How do I determine whether an electric shock is clicked or double-clicked?

A: The Code is as follows:

-(Void) touchesEne: (NSSet *) touches withEvent: (UIEvent *) event {

NSSet * allTouches = [event allTouches];

Switch ([allTouches count]) {

Case 1:

UITouch * touch = [[allTouches allObjects] objectAtIndex: 0];

Switch ([touchTapCount]) {

Case 1:

// Single Machine

Break;

Case 2:

// Double-click

Break;

Default:

Break;

}

 

Default:

Break;

}

}

 

 

 

27. What is the Coco2d event processing mechanism?

A: I didn't understand the tutorial. [reserved].

 

 

28. What are the types of maps on the mobile phone based on the scrolling mode?

Answer: Class 3;

(1) Vertical scrolling

Airplane games

(2) horizontal scrolling

Super Mary

(3) horizontal and vertical scrolling

RPG class.

29. What problems do I mainly consider when creating a scenario map?

A:

(1) Moving position control: when the main character moves on the map, the obstacle of the objects in the map must be taken into account. The main character cannot cross the wall and must cross the river through the wooden bridge. A more realistic simulation requires the protagonist to have different moving speeds on different ground.

(2) dynamic map changes: the actions of the protagonist in the game lead to map changes (permanent changes, not temporary changes, such as: the enemy's bodies rot and slowly disappear, this effect does not involve modifying the map ). destroy enemy buildings and build our buildings

 

30. What should I consider in map programming?

A:

(1) how to display a large map scenario.

(2) movement restrictions on the genie on the map.

(3) how to dynamically change the display content of a local map

 

31. How do I set the startup landscape of the Cocos2d-iphone program?

A: In the rootviewcontroller. M file.

Find the following code:

# Elif game_autorotation = kgameautorotationuiviewcontroller

...

Return (UIInterfaceOrientationIsLandscape(Interfaceorientation ));

// Return (UIInterfaceOrientationIsPortrait(Interfaceorientation ));

 

 

32. What is the role of the map editor tool? (Tiled map editor, http://mapeditor.org /)

A: map editor draws scene maps. The generated maps are in the *. tmx format (essentially an XML file ).

Note: The generated map must be placed with the *. PNG image of the map element.

 

33. What are the performance of Cocos2d-iphone's support for tiled map plotting tools?

(1) map type

& Amp; orthogonal isometric full support

& Hexagonal support

(2) "tile" Gallery

& The image file cannot be saved *. the gallery of embedded "tiles" in the tmx file. only the external "tile" Gallery is supported. that is to say, a map must be composed of a tmx file and an image file.

(3) Layer

& Cocos2d-iphone supports any number of layers

& The corresponding programming interface class for each layer is tmxlayer (subclass of atlasspritemanager)

& The programming interface class corresponding to each "tile" is atlassprite

 

 

34. What are the two main component files that Cocos2d-iphone implements Map Display?

Answer: & Responsible for displaying the overall map: cctmxtiledmap. h cctmxtiledmap. m

& Reads and parses XML files: cctmxxmlparser. h cctmxxmlparser. m

 

35. How can I load game maps?

Answer: CCTMXTiledMap * gameWorld = [CCTMXTiledMap tiledMapWithFile: @ "Level1.tmx"];

[Self addChild: gameWorld z: 0 tag: 9];

 

36. What is the role of CCTMXLayer?

A: CCTMXLayer is a subclass of CCSpriteBatchNode. We know that CCSpriteBatchNode caches all images. The function of CCTMXLayer is to cache map images, in this way, we can use the "tile" unit to obtain different "tiles" on the map ".

 

 

 

37. What does 30 frames/Second Mean?

A: The image engine constantly draws the virtual world depicted by memory data to the IPHONE screen at 30 times per second.

 

 

38. Three independent program logics constitute the main programming model of the game program. What are the three types?

A:

(1) When the user inputs: "Touch" or gravity sensing, the player genie issues various commands

(2) AI engine commands: various commands issued by the system to non-player genie

(3) Various timing Logics: Specify the first two categories to directly modify the Game Genie status.

Various timing logics determine possible wizard or environment changes based on the mutual location information of various genie.

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.