Cocos2d-android game engine-Introduction

Source: Internet
Author: User

I. Game Engine Concept

What is a game engine?
A game engine is a core component of an editable game system or interactive real-time image application. These systems provide game designers with a variety of tools required to write games, with the aim of enabling game designers to easily and quickly make game programs without starting from scratch.
Cocos2d family
Cocos2d is an open-source game development framework that can be used to easily develop 2D games. Including the following members
Cocos2d-x
Cocos2d-iphone
Cocos2d-android
Essential difference: the language of development is different: Cocos2d-x using c ++, Cocos2d-iphone using Object-C
Commonalities: the api names are basically the same.
Why should we use cocos2d?
An open-source, cross-platform, and lightweight 2D game engine.
Good performance
Extensive community support
Supports many success stories. For example, fishing talents and Three Kingdoms tower defense
Use the MIT authorization protocol. Free to use, modify the source code, do not need to publish the source code like GPL, can be commercialized

Ii. cocos2d Architecture


Iii. Architecture Description

Graphics engine Cocos2D Graphic
Sound engine CocosDenshion Audio
Physical Engine
Box2d
Chipmunk
Script library Lua

Iv. Graphic engine Cocos2D Graphic


Unified management of CCDirector Interface

I. Image Engine description

Graph engine description
CCDirector (Director)
Engine controllers, switching of control scenarios, and game engine attribute settings
CCScene (scenario)
Scenarios, such as game pop-up screens, main menus, and main game interfaces.
CCLayer)
Layer class, each layer has its own trigger event, this event can only be valid for its own elements, and the elements contained in the elements on the layer are not managed by its events
CCSprite (character)
The smallest unit displayed on the interface.
CCNode
The most important element in the engine, all the things that can be drawn are derived from this. It can contain other ccnodes, can execute timer operations, and can execute CCAction.
CCAction)
Operations, such as translation, scaling, and Rotation



Ii. CCDirector

CCGLSurfaceView
The SurfaceView subclass in the engine implements the SurfaceHolder. Callback interface, but does not implement the Runnable interface.
Problems:
1. Who is the thread used to draw the interface?
2. How is this thread started?
Role of CCDirector
The drawing of the interface is completed by GLThread, and the opening of GLThread is completed in the CCDirector attachInView method.
Management scenario CCScene


Summary of main methods:
Object acquisition:
Shareddire() gets the object
Start the drawing thread
AttachInView () connection SurfaceView
Scenario Management
RunWithScene () Running scenario
ReplaceScene () replacement scenario
Lifecycle
Resume () enters the running status
Pause () pause
End () ends
Screen Switching
SetDeviceOrientation ()
SetScreenSize (480,320) sets the screen resolution. When the screen resolution is higher than the set resolution, the engine automatically adapts. The engine divides the screen horizontally into 480 sets and vertically into 320 sets, the values used in the Code are calculated relative to these values.
Frame Rate Settings
SetDisplayFPS (true) indicates the fps frame rate. Display of the frame rate into the assets folder.
SetAnimationInterval (1.0f/60) sets the frame rate and refreshes 60 times per second.

Iii. CCScene

Scenario CCScene
Currently, this class does not have any specific functions. It only serves as the root node of the content to be displayed in a project.

Iv. CCLayer

Layer or set
Call addChild (CCNode child) to add a wizard
You can add CCLayer (similar to VIewGroup) under CCLayer)
The user's TouchEvents event can be processed on the CCLayer.
Usage: Write a Layer to inherit the CCLayer and process its onTouch events.
Note: You need to set setIsTouchEnabled (true) so that your Layer can accept the Touch event.

V. CCSprite)
1. Origin
The current coordinate system, which specifies that the coordinate origin is in the lower left corner of the screen. Use sprite. getPosition () to obtain the coordinates of the currently loaded genie.
2. anchor point)
① When displaying CCSprite, you need to set the anchpoint information. The default value is (0.5f, 0.5f). The intermediate point of the CCSprite image is used as the benchmark of the image in the current coordinate system. getAnchorPoint () obtains the anchpoint information of the current genie.
② Set the anchorpoint: When setRelativeAnchorPoint (false) is set to (0, 0), or when setAnchorPoint is called to specify relevant information, the setRelativeAnchorPoint method is invalid when setAnchorPoint is called.


3. Summary of Main Methods
① Anchor
SetRelativeAnchorPoint (boolean relative) is used to set the lookup point. The default value is true. When the anchor is set to (0, 0), false is used.
SetAnchorPoint (float x, float y) sets the specified value of the anchorpoint. The overload method setAnchorPoint (CGPoint anchor) encapsulates the information of x and y.
② Coordinates
SetPosition (float x, float y) sets the coordinates of the genie.
③ Image
SetFlipX (true) is an image on the X axis, and setFlipY (true) is an image on the Y axis to reuse image resources.
④ Transparency
The smaller the value, the more transparent the value is.
⑤ Add genie
AddChild (CCNode child) Adds a child to the container with z-order as 0. The display order is determined based on the order of addition, that is, the last added display is at the frontend.
AddChild (CCNode child, int z) Adds a child to the container with a z-order. A greater value indicates a higher priority.
AddChild (CCNode child, int z, int tag) Adds a child to the container with z order and tag. Tag specifies the sprite id. The default value is-1.


4. Analysis of CCSprite click events
① Basis for determining whether a CCSprite object is clicked
In the small example described above, we learned that it is based on the user's clicking on the coordinates on the screen to determine whether a user has clicked an image with certain buttons.
In cocos2d, we also need to determine which CCSprite object was clicked Based on the coordinates of the user's click screen. However, since the coordinate system has been adjusted in cocos2d, You need to unify the two coordinate systems when determining whether they are clicked.
In addition, since each sprite corresponds to only one coordinate value, when determining whether the CCSprite object is clicked, You need to obtain the range of the entire CCSprite object on the screen, the width and height of the CCSprite object are also obtained.


② It should be noted that the processing of user touch events is in the CCLayer.
5. CCSprite Click Event Processing
Steps:
① Create class MyCCLayer inherits the CCLayer class and overwrites the handling method of user touch screen events
@ Override
Public boolean ccTouchesBegan (MotionEvent event ){
Return super. ccTouchesBegan (event );
}
@ Override
Public boolean ccTouchesEnded (MotionEvent event ){
Return super. ccTouchesEnded (event );
}
@ Override
Public boolean ccTouchesMoved (MotionEvent event ){
Return super. ccTouchesMoved (event );
}
② Convert the screen coordinates to the cocos2d Coordinate System
Call CCNode. convertTouchToNodeSpace (MotionEvent event) to convert the user-clicked coordinate information encapsulated in the event to the CGPoint object.
③ Determine whether the CGPoint object is within the scope of the CCSprite object
6. Determine whether the CGPoint object is within the scope of the CCSprite object
① Judgment Thoughts
Get the current CCSprite object, and use getChildByTag (int)
Calculate the rectangle range occupied by the CCSprite object. The CCNode. getBoundingBox () method can obtain the rectangle range occupied by the CCSprite object, which is encapsulated in the CGRect information.
Determine whether a user's touch point is included in CGRect, and use the CGRect method containsPoint to judge
② Note: To enable the CCLayer to handle user touch screen events, you need to set the current CCLayer. setIsTouchEnabled (true );


Vi. CCAction
For a game, action is very important. Good actions can greatly improve the playability of the game. There is a category in the cocos2d engine, and CCAction is the base class of the category class, an action is defined on a node (CCNode). It targets nodes and is divided into two types: instantaneous action and delayed action.




1. CCIntervalAction (delayed action)
2. The basic latency actions provided by Cocos2d both provide ActionTo and ActionBy (seven types ):
ActionTo refers to the end of an action, that is, the end of the action.
ActionBy refers to the action execution status, that is, the action execution process.
3. Common latency classes include:
Mobile action: CCMoveBy CCMoveTo
Scaling action: CCScaleByCCScaleTo
Rotation action: CCRotateByCCRotateTo
Hop action: CCJumpBy CCJumpTo
Besell curve action: CCBezierByCCBezierTo
Fade in and fade out action: CCFadeByCCFadeIn CCFadeOut
......


VII. CCIntervalAction)
1. Location change
Move)
Bounce (jump)
Beiser curve Motion)
EaseIn)
EaseOut)
Fast first and slow later
Special effects, buffering before acceleration
Sine curve speed change
2. Fixed Point changes
Scale)
Rotate)
Color gradient (Tint)
Blink)
Playback sequence Frame


CCIntervalAction)
Perform actions in sequence
Execute the action to be executed at the same time
Intermittent action (the specified time is paused in the middle)


VIII. About CCAction
1. CCAction -- move (CCMoveBy and CCMoveTo)
Create object: Use CCMoveBy (To). action (float duration, CGPoint pos ).
Parameter description: duration. pos indicates the target point.
Differences: ① The CGPoint specified by CCMoveBy is the relative coordinate, that is, the genie to be moved relative to the current one. CCMoveTo specifies that CGPoint is the absolute coordinate. ② CCMoveBy processes the reverse () method, while CCMoveTo returns null. It is easy to use CCMoveBy when we need to implement repeated movements of the genie.
Application Scenario: if the game passes the game, an arrow will repeatedly remind you of your route forward. First, we need to use CCSequence to add the effects of a group of moves to achieve a single round trip, and then use CCRepeatForever to implement repeated actions.
2. CCAction -- bounce (CCJumpBy and CCJumpTo)
Creation object: CCJumpBy (To). action (float time, CGPoint pos, float height, int jumps)
Parameter description: time indicates the duration, pos indicates the target point, height indicates the height of the drop, and jumps indicates the number of beats.
Difference: CCJumpBy processes the reverse () method and can be used to implement repeated actions;
Application scenarios:
3. CCAction-besell curve motion (CCBezierBy)
Object created: CCBezierBy (To). action (float t, CCBezierConfig c)
Parameter description: t indicates the duration, c curve parameter, CCBezierConfig. controlPoint_1 start point, CCBezierConfig. controlPoint_2 vertex, and CCBezierConfig. endPosition end point.
Application Scenario: Bullet, roof level in pvz
4. CCAction-CCEaseIn)
Object creation: CCEaseIn. action (CCIntervalAction action, float rate)
Parameter description: The action controlled by the action, rate acceleration. If it is 1, the constant speed is reached.
Slow down: the CCEaseOut and CCEaseIn parameters are the same, but the action is the opposite.
5. CCAction-Scaling (CCScaleBy and CCScaleTo)
Creation object: CCScaleBy (To). action (float t, float s)
Parameter description: t represents the duration, and s represents the scaling ratio.
Difference: CCScaleBy processes the reverse () method and can be used to implement repeated actions.
Application Scenario: heartbeat
6. CCAction -- rotate (CCRotateBy and CCRotateTo)
Object created: CCRotateBy (To). action (float t, float)
Parameter description: t indicates the duration, and a indicates the rotation angle.
Difference: ① CCScaleBy processes the reverse () method and can be used for repeated actions; ② CCRotateTo rotates to the specified angle in the most convenient way, such as when the rotation angle is 300, if CCRotateTo is used, it will rotate 60 degrees counterclockwise.
Application scenarios: progress bar rotation, left and right swing of the flag, etc.
Note: The rotation is completed along the anchor. Therefore, you must coordinate the rotation with the anchor.
7. CCAction-color gradient action (CCTintBy and CCTintTo)
Creation object: CCTintBy (To). action (float t, ccColor3B c)
Parameter description: t: time interval, c: RGB three-color value encapsulated object
Differences: ① CCTintBy implements the reverse () method; ② the RGB values to be set for CCTintBy are relative values, that is, changes relative to the current RGB values.
Application scenarios
8. CCAction -- blinking (CCBlink)
Object creation: CCBlink. action (float t, int B)
Parameter description: t interval, number of B flashes
9. CCAction-playing sequence Frame
Playback sequence Frame
CCAnimation Loading
CCAnimate
You can use stopAction to stop playback.
10. CCAction-continuous action CCSequence
Object creation: CCSequence. actions (CCFiniteTimeAction action1, CCFiniteTimeAction... actions)
Object Description: used to perform a series of actions in sequence.
11. CCAction -- Concurrent Action CCSpawn
Object creation: CCSpawn. actions (CCFiniteTimeAction action1, CCFiniteTimeAction... params)
Parameter description: specifies that a series of actions are triggered at the same time, for example, performing a flip action during the jump process.
12. CCAction-intermittent action (CCDelayTime)
Object creation: CCDelayTime. action (float t)
Parameter description: t stop time
13. instant action)
Instantaneous action: an action that is completed immediately without time.
Cocos2d provides the following instantaneous actions:
The placement-Place effect is similar to node. Position = ccp (x, y ). It is implemented as an action to form a continuous action with other actions.
The hidden-Hide effect is similar to [node setVisible: NO]. It is implemented as a sequence to form a continuous action with other actions.
The display-Show effect is similar to [node setVisible: YES]. It is implemented as an action to form a continuous action with other actions.
Visible switch-ToggleVisibility
14. CCAction -- show and hide
Visibility (CCHide and CCShow)
Object creation: Call the action method without parameters.
15. CCAction-unlimited action CCRepeatForever
Unlimited execution of a delayed action is usually used for consecutive execution of a series of repeated actions, which are mostly defined in CCSequence.


IX. CocosDenshion Audio sound engine
SoundEngine processing sound
Sound type: music and sound effects
It can be distinguished from the length. Music is generally used for the background sound of the game. The sound effect is mainly short sound, such as the bullet emitted by plants and the sound emitted by botnets when they eat plants.
Sound control, such as playback, pause, sound size adjustment, and mute
Improves audio processing efficiency by caching music and audio files

X. Summary

Having talked about so many cocos2d game engine APIs, isn't it boring. Okay, now I will use these APIs to design a small Dome

For more information about Dome, see the next blog...










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.