Cocos2d-android Game Engine-Introduction

Source: Internet
Author: User
Tags addchild

First, the game engine concept

What is a game engine
The game engine is the core component of some well-written editable game systems or some interactive real-time image applications. These systems provide game designers with a variety of tools to write games that are designed to allow game designers to make game programs easy and fast without starting with 0.
Cocos2d Family
Cocos2d is an open-source game development framework that makes it easy to develop 2D games. Include the following members
Cocos2d-x
Cocos2d-iphone
Cocos2d-android
Essential difference: The language of development is different: Cocos2d-x use C + +, Cocos2d-iphone use Object-c
Common denominator: API names are basically the same
Why do we use cocos2d
An open-source, cross-platform, lightweight 2D game engine.
Good performance
Extensive community support
Support a lot of success stories. For example, fishing, the Three Kingdoms Tower defense.
Use the MIT licensing agreement. Be free to use, change source code, do not need to open source code like GPL, can be commercially

Second, cocos2d structure


Iii. Description of the architecture

Graphics Engine cocos2d Graphic
Sound Engine cocosdenshion Audio
Physics engine
Box2d
Chipmunk
Script Library Lua

Four, graphics engine cocos2d Graphic


Unified Manager of Ccdirector interface

Ⅰ, Image engine description

Graphics Engine Description
Ccdirector (director)
Engine controller, Control scene switch, game engine properties settings
Ccscene (Scene)
The scene class, such as the game splash screen, main menu, game main interface and so on.
Cclayer (Scene)
Layer classes, each layer has its own trigger event, which only works on the elements it owns, and the elements on top of the layer are not managed by its events
Ccsprite (People)
Elf class, 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 include other ccnode, be able to run timer operation, and be able to run ccaction.
Ccaction (Action)
Action classes, such as panning, zooming, rotating, and so on



Ⅱ, Ccdirector

Ccglsurfaceview
The Surfaceview subclass in the engine implements the Surfaceholder.callback interface, but does not implement the Runnable interface.
A problem exists:
1. Who is the thread that draws the interface?
2. How does the thread start?
The role of Ccdirector
The drawing of the interface is done by Glthread, and the Glthread is completed in Ccdirector Attachinview method.
Management Scenario Ccscene


Summary of Main methods:
object is obtained:
Shareddirector () Get the object
Start the paint thread
Attachinview () connection Surfaceview
Management of the scene
Runwithscene () Execution Scenario
Replacescene () Replace scene
Life cycle
Resume () Enter execution state
Pause () pauses
End () ends
Screen switching
Setdeviceorientation () Setting Horizontal screen vertical screen
Setscreensize (480, 320) sets the screen resolution, higher than the set resolution, the engine will be self-adaptive, the engine will be divided horizontally into 480 parts of the screen, the vertical direction is divided into 320 parts, the code used in the value is calculated relative to these
Frame rate Setting
Setdisplayfps (true) shows FPS frame rate. The frame rate display needs to add the Fps_images.png picture to the assets directory
Setanimationinterval (1.0F/60) Set frame rate, refresh 60 times per second

Ⅲ, Ccscene

Scene Ccscene
There is no detailed function of this class at the moment, it is simply the presence of the root node that needs to be presented as part of a project.

Ⅳ, Cclayer

Layer or scene
Call Addchild (Ccnode Child) method to join the wizard
Ability to add cclayer (similar to viewgroup) under Cclayer
Ability to handle user's Touchevents events on Cclayer.
Usage: Write a layer to inherit the Cclayer and handle its own Ontouch event.
Note: You need to set setistouchenabled (true) to allow your layer to accept the touch event.

Ⅴ, Ccsprite (elf)
1. Origin
The current coordinate system, which specifies that the lower left corner of the screen is the origin of the coordinates. Gets the coordinate value of the currently loaded sprite through Sprite.getposition ().
2. Anchor (anchor Point)
①ccsprite display when the need to set the anchor information, 0.5f,0.5f, will be ccsprite the middle point of the picture as the picture in the current coordinate system of the datum point, through the Sprite.getanchorpoint () to get the current Genie's anchor point information.
② Anchor Point setting: Setrelativeanchorpoint (False) when the anchor point is (0,0) or call Setanchorpoint to specify the relevant information, Setrelativeanchorpoint method is invalid when calling Setanchorpoint


3. Summary of Main methods
① Anchor Point
Setrelativeanchorpoint (Boolean relative) sets the stroke, the default value is true, when the anchor point is set (0,0), false is used
Setanchorpoint (float x, float y) sets the anchor point specified value, Overloads method Setanchorpoint (Cgpoint anchor), Cgpoint encapsulates x, y information
② coordinates
SetPosition (float x, float y) sets the wizard's coordinate information
③ Mirroring
SETFLIPX (true) mirroring on the x-axis, setflipy (true) mirroring on the y-axis, with the goal of reusing picture resources
④ Transparency
setopacity (int) 0-255, the smaller the value the more transparent, the less transparent
⑤ Join the Genie
AddChild (Ccnode Child) Adds A-the container with Z-order as 0. Depending on the order of accession, the display is sequential, that is, the post-join display is at the forefront.
AddChild (Ccnode child, int. z) Adds a child to the container with a z-order. A larger value displays a higher priority.
AddChild (ccnode child, int z, int. tag) Adds a child to the container with Z order and tag. TAG specifies the ID of the genie, the default value is-1.


4. Ccsprite Click event Analysis
①ccsprite whether the object is clicked is inferred according to
In the example in the previous illustration, we learned that if the user clicked on some of the button's images, the user clicked on the screen coordinates.
In cocos2d we also need to infer which Ccsprite object is clicked based on the coordinates of the user tapping the screen. However, since the coordinate system has been adjusted in cocos2d, it is necessary to unify the two coordinate systems when the inference is clicked.
In addition, because each sprite only corresponds to a coordinate value, it is necessary to obtain the entire Ccsprite object's coverage on the screen when it is inferred that the Ccsprite object is clicked, which needs to be combined with the anchor information to obtain the width and height of the Ccsprite object at the same time.


② Special need to note is that the handling of user touch events is in the Cclayer.
5. Ccsprite Click event Handling
Implementation steps:
① Creating Class Mycclayer inheriting the Cclayer class, overriding the handling 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);
}
② converting screen coordinates to cocos2d coordinate system
Call Ccnode.converttouchtonodespace (Motionevent event) to convert the encapsulated user in event to Cgpoint object by clicking the coordinate information
③ infers whether the Cgpoint object is within the scope of the Ccsprite object
6. Infer if the Cgpoint object is within the range of the Ccsprite object
① Inference thought
Gets the current Ccsprite object, using Getchildbytag (int)
Calculating the rectangular extent of the screen occupied by this Ccsprite object, the Ccnode.getboundingbox () method is able to obtain the rectangular extents occupied by the Ccsprite object, which is encapsulated in the CGRect information.
Infer whether the user's touch points are included in the CGRect, using CGRect's method Containspoint inference
② Special Note: Assume that the Cclayer can handle user touch screen events need to set the current cclayer.setistouchenabled (true);


ⅵ, ccaction
for a game, the action is very important, good action can make the game greatly improve the playability, there is an action class in the Cocos2d engine, Ccaction is the base class of the action class, The action is defined on the node (ccnode), the node as the target, mainly divided into two categories: instantaneous action and delay action  




1, ccintervalaction (delay action)
2, COCOS2D provides the basic delay class actions are provided ACTIONTo and Actionby two species (seven kinds):
ACTIONTo refers to the state of the end of action, that is, the end of the action.
Actionby refers to the state of the movement, that is, the movement of the operation process.
3. The frequently used Delay action class contains:
Move action: Ccmoveby Ccmoveto
Zoom action: CcscalebyCcscaleto
Rotary action: CcrotatebyCcrotateto
Jumping action: ccjumpby Ccjumpto
Bézier curve Action: CcbezierbyCcbezierto
Fade action: Ccfadebyccfadein ccfadeout
......


Ⅶ, ccintervalaction (Basic action)
1. Change of position
Mobile (move)
Bounce (Jump)
Bézier curve Motion (Bézier)
Fade (EaseIn)
Slow (EaseOut)
Fade out and slow down first
Special effects, first buffering and then accelerating
Sinusoidal speed Change
2. Fixed-point change
Scaling (Scale)
Rotation (Rotate)
Color Gradient Action (Tint)
Flashing (Blink)
Play sequence Frames


Ccintervalaction (combined action)
Run actions sequentially
The same time running the action to be run
Intermittent action (middle pause for specified time)


Ⅷ, about Ccaction
1. ccaction--movement (Ccmoveby and Ccmoveto)
Create object: Take advantage of Ccmoveby (to). Action (float duration, cgpoint pos).
Parameter Description: Duration duration, POS stands for Target point
Different points: ①ccmoveby Specifies that the cgpoint is relative to the current need to move the sprite. Ccmoveto Specifies that the cgpoint is an absolute coordinate. ②ccmoveby the reverse () method is processed, and Ccmoveto returns a null value. It's very easy to use ccmoveby when we need to implement the sprite's repetitive movement.
Application Scenario: If the game passes, there will be an arrow to repeat the route you are going forward. First we need to use ccsequence to add a set of moving effects together to achieve a single round trip, and then use ccrepeatforever to achieve repetitive actions.
2. ccaction--Bounce (Ccjumpby and Ccjumpto)
Created object: Ccjumpby (to). Action (float time, cgpoint pos, float height, int jumps)
Description: Time represents the Duration, POS represents the target point, height represents the fall height, jumps represents the number of Beats
Difference: Ccjumpby the reverse () method, which can be used to realize the repeated action;
Application Scenarios:
3. ccaction--Bezier Curve Motion (Ccbezierby)
Created object: Ccbezierby (to). Action (float T, Ccbezierconfig c)
Description: T represents duration, C curve parameters, ccbezierconfig.controlpoint_1 starting point, ccbezierconfig.controlpoint_2 Vertex, Ccbezierconfig.endposition End
Application scenario: Bullet, PvZ roof level
4, ccaction--fast (Cceasein)
Object creation: Cceasein.action (ccintervalaction action, float rate)
Description: Action controlled actions, rate acceleration, assuming 1 is uniform.
Slow: Cceaseout is the same as the Cceasein, the opposite of the action
5, ccaction--Zoom (Ccscaleby and Ccscaleto)
Create object: Ccscaleby (to). Action (float T, float s)
Description: T stands for Duration, S represents zoom ratio
Difference: Ccscaleby the reverse () method and can be used to perform repetitive actions
Application Scenario: Heartbeat
6, ccaction--rotation (Ccrotateby and Ccrotateto)
Create object: Ccrotateby (to). Action (float T, float a)
Description: T for duration, a for angle of rotation
Difference: ①ccscaleby the reverse () method, which can be used to achieve repetitive actions, ②ccrotateto rotate to a specified angle in the most convenient way, such as when the rotation angle is 300, the use of Ccrotateto to achieve the counter-clockwise rotation 60 degrees
Application Scenario: Progress bar rotation, flag swing left and right, etc.
Special Note: The rotation action is completed along the anchor point, so it is necessary to unify and coordinate the rotation action with the anchor point.
7, ccaction--color gradient action (Cctintby and Cctintto)
Create object: Cctintby (To). Action (float T, cccolor3b c)
Number of parameters: T: time interval, C:rgb three-color value encapsulated object
Difference: ①cctintby to reverse () method; ②cctintby the RGB tri-color value you need to set is a relative value, which is a change from the current RGB value.
Application Scenarios
8, ccaction--flashing (Ccblink)
Object creation: ccblink.action (float t, int b)
Number of parameters: T interval, b blink times
9. ccaction--Play Sequence Frame
Play sequence Frames
Ccanimation loading
Ccanimate
If you want to stop playback, you can use Stopaction
10, ccaction--continuous action ccsequence
Object creation: Ccsequence.actions (ccfinitetimeaction action1, ccfinitetimeaction ... actions)
Object Description: Used to run a series of actions sequentially
11. ccaction--Concurrent Action Ccspawn
Object creation: Ccspawn.actions (ccfinitetimeaction action1, ccfinitetimeaction ... params)
Parameter description: Specifies that a sequence of actions is triggered at the same time, such as running a rollover action during a jump.
12, ccaction--intermittent action (ccdelaytime)
Object creation: Ccdelaytime. Action (float t)
Parameter description: T stop time
13. Instant Action (ccinstantaction)
Instantaneous action: It is the action that does not need time, immediately completes.
The COCOS2D provides the following instantaneous action:
Placing the –place effect is similar to node. Position = CCP (x, y). It is implemented as an action to be able to form a continuous action with other actions.
The hidden –hide effect is similar to [node Setvisible:no]. This is done as a movement to be able to form a continuous action with other movements.
The display –show effect is similar to [node Setvisible:yes]. It is implemented as an action to be able to form a continuous action with other actions.
Visible Toggle –togglevisibility
14, ccaction--Show hidden
Visibility (Cchide and Ccshow)
Object creation: You can call the action method, no parameters
15, ccaction--Infinite action Ccrepeatforever
Unrestricted operation of a delay action, often used in continuous running a series of repeated actions, these actions are placed in the ccsequence to define.


Ⅸ, Cocosdenshion audio sound engine
Soundengine Handling Sound
Sound type: music and sound effects
Can be distinguished from the length, the music is generally used for the background sound of the game, the sound is mainly short sound, such as the plant fired bullets, zombies eat the sound of plants
Sound control, such as play, pause, sound size adjustment, mute
Improve the efficiency of sound processing by caching music and sound effects files

Ⅹ, summary

Speaking of so many cocos2d game engine API, do not feel a bit boring. Okay, so I'm going to use these APIs to design a little dome.

Want to know how dome, and read the next blog post ...










Cocos2d-android Game Engine-Introduction

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.