Ios_31_cocos2d_ Layer Cclayer_ Accelerometer

Source: Internet
Author: User
Tags addchild

Final:
Cocos2d-x, the inheritance structure of layer layers:
As you can see from the image above: several direct sub-categories of emphasis are: Control, ScrollView, Menu, Layercolor where Layercolor can make a layer color the subclass of control, which is all the classes that interact with the user, such as: button, slider, etc. 0. Cclayer Overview A game can have a lot of scenes, each scene may contain more than one layer, The layers here are generally cclayer objects. The cclayer itself has almost no function, The contrast Ccnode,cclayer can be used to receive touch and accelerometer inputs. ( userinteractionenabled is yes)In fact, Cocos2d does not have strict requirements on the layer, the layer does not have to use the Cclayer class, It can also be a simple ccnode because a new layer is created to accommodate more child nodes, Ccnode can also add child nodes. So, if the layer does not need to receive touch and accelerometer input, use Ccnode to represent the layer as much as possible Cclayer because it can receive touch and accelerometer input, it adds unnecessary overhead. move, scale, and rotate the entire layer, and all the nodes on the layer will move, scale, and rotate along with it. Note: In Cocos2d V3, Cclayer has been canceled
Note: cocos2d v3 version, because Cclayer is no longer used, scene scenes after complying with the agreement <CCAccelerometerDelegate>, can directly Monitor Accelerometer Events ,
when the phone is upright, the X-direction acceleration value is approximately equal to 0
when the phone tilts to the right, the acceleration value in the X direction increases

When the phone tilts completely to the right, the acceleration value in x direction is approximately equal to +1.0

when the phone tilts to the left, the acceleration value in the X direction decreases

When the phone tilts completely to the left, the acceleration value in the x direction is approximately equal to -1.0

as shown in the following code:
accelerometerscene.m//31_cocos2d Primer////Created by Beyond on 14-9-27.//Copyright (c) 2014 Com.beyond. All Rights reserved.//Realization: The mobile phone tilted to the right, in the center of the nanasprite to the right, the phone tilted to the left, in the center of the nanasprite to the left; #import "AccelerometerScene.h"// To listen for accelerometer events, you must comply with Protocols <CCAccelerometerDelegate> @interface Accelerometerscene () <ccaccelerometerdelegate>{/ /principle: In the monitoring accelerometer method, record Accelerameterx, in the clock Method update Shepherds The wizard position cgfloat _accelerationx;}        @end @implementation Accelerometerscene#pragma Mark-Override Parent class method-(ID) init{if (self=[super init]) {///1, Scene node allows interaction            self.userinteractionenabled = YES; } return self;} Implement the method of the parent class, add a button to the screen-(void) addshowbtns{} #pragma mark-Accelerometer proxy method//scene must first comply with protocol ccaccelerometerdelegate//Unlike touch events, accelerometer events, only One method is: didaccelerate-(void) Accelerometer: (Uiaccelerometer *) Accelerometer didaccelerate: (Uiacceleration *) acceleration{//Range is:-1 ~ 1, for example: X, the cell phone in the vertical state, to the right tilt, x from 0 gradually increased to +1//x, the phone vertical state, left tilt, x from 0 gradually reduced to 1 cclog (@ "x=%f, y=%f, z=%f", Acceleration.x, AcceleratiON.Y, ACCELERATION.Z);    sensitivity int Lingmindu = 6; _accelerationx = acceleration.x * LINGMINDU;} The only thing to note about, layers, accelerometers: In the monitoring accelerometer method, the value of the accelerometer is recorded, and the position of the sprite can only be set when the update brush frame is made; This is done to ensure that the picture is smooth!!! Because the Update method, 1 seconds can be called 60 times, and the accelerometer's listening method, 1 seconds to call 10 times-(void) update{self.sprite.position = Ccpadd (Self.sprite.position, CCP (6, 0));} @end


cocos2d v3 The practice of touching events:

setting up a scene Node allows interaction

Self . userinteractionenabled =YES;



here are the previous usages of cocos2d v3:

Cclayer Common Settings

1. Receive Touch input

Cclayer The default is not to receive touch input, you need to display the istouchenabled set to Yes

self.istouchenabled = YES;
after setting istouchenabled to Yes, the layer's corresponding method is called to handle the touch input:

These are the methods defined in the Ccstandardtouchdelegate protocol

1> when a single finger touches the screen

<span style= "FONT-SIZE:18PX;" >-(void) Cctouchesbegan: (Nsset *) touches withevent: (uievent *) event;</span>

2> when the finger moves on the screen

<span style= "FONT-SIZE:18PX;" >-(void) cctouchesmoved: (Nsset *) touches withevent: (uievent *) event;</span>

3> when a single finger leaves the screen

<span style= "FONT-SIZE:18PX;" >-(void) cctouchesended: (Nsset *) touches withevent: (uievent *) event;</span>

4> when the touch is canceled

<span style= "FONT-SIZE:18PX;" >-(void) cctouchescancelled: (Nsset *) touches withevent: (uievent *) event;</span>

There is very few cases where the touch is canceled,

So most of the cases can be ignored, or replaced with cctouchesended,

Because cctouchescancelled and cctouchesended are similar.


In most cases, you need to know where the touch occurs. The touch event here is received by the Uikit framework, so the touch location needs to be converted to OpenGL coordinates.

For example, in the process of finger movement:

-(void) cctouchesmoved: (Nsset *) touches withevent: (Uievent *) event {    //Get Touch object    uitouch *touch = [touches Anyobject];    Gets the position of the touch on the UIView view    cgpoint uipoint = [Touch LocationInView:touch.view];    Convert to OpenGL coordinates    cgpoint glpoint = [[Ccdirector shareddirector] converttogl:uipoint];}


Here is a small example of how to use the above method, assuming that there is a sprite on the layer, where the finger touches, where the sprite is located

First add the sprite when the layer is initialized

The Init method of the layer-(ID) init{if ((Self=[super init])) {//Initialize an elf ccsprite *nana = [Ccsprite spritewithfile:@        "Nana.png"];        Cgsize size = [[Ccdirector shareddirector] winsize];        Nana.position = CCP (Size.width * 0.5f, Size.Height * 0.5f);                Add the genie and set the tag [self Addchild:nana z:0 tag:knanatag];    self.istouchenabled = YES; } return self;}


The next step is to receive touch input in the layer

Calculate the position of the touch in the layer (OpenGL coordinates)-(Cgpoint) Locationinlayer: (Nsset *) touches {//Get Touch object Uitouch *touch = [touches anyobject]    ;    Gets the position of the touch on the UIView view cgpoint uipoint = [Touch LocationInView:touch.view];        Convert to opengl coordinates cgpoint glpoint = [[Ccdirector shareddirector] converttogl:uipoint]; return glpoint;}    Since Cctouchesbegan, cctouchesmoved, and cctouchesended are all the same, a method-(void) Dealtouches: (Nsset *) touches {//calculates the location of the touch    Cgpoint point = [self locationinlayer:touches];    Get the sprite ccsprite *nana = (Ccsprite *) based on the tag [self getchildbytag:knanatag]; Set the location of the sprite nana.position = point;} -(void) Cctouchesbegan: (Nsset *) touches withevent: (Uievent *) event {[Self dealtouches:touches];} -(void) cctouchesmoved: (Nsset *) touches withevent: (Uievent *) event {[Self dealtouches:touches];} -(void) cctouchesended: (Nsset *) touches withevent: (Uievent *) event {[Self dealtouches:touches];}

Above is the touch input of the layer before COCOS2D v3


2.coco2d v3 before the accelerometer event

Cclayer The default is not to receive the accelerometer input, you need to set the isaccelerometerenabled to show to Yes

self.isaccelerometerenabled = YES;
after setting isaccelerometerenabled to Yes, the layer's corresponding method is called to process the accelerometer input:

This is the method defined in the uiaccelerometerdelegate protocol

-(void) Accelerometer: (Uiaccelerometer *) Accelerometer didaccelerate: (Uiacceleration *) acceleration {    //typedef    Double Uiaccelerationvalue;    Uiaccelerationvalue x = acceleration.x;    Uiaccelerationvalue y = acceleration.y;    Uiaccelerationvalue z = acceleration.z; X, Y, z represent acceleration}<span style= "font-size:18px in any direction in three dimensions." ></span>


3, Cclayercolor

By default, Cclayer is not able to set the color,

Sometimes, you want to set a background color for the entire layer,

Then we need to use the Cclayercolor.

Cclayercolor is a subclass of Cclayer

Red: #ffff0000ccColor4B color = ccc4 (255, 0, 0, 255);//Initialize a color layer cclayercolor *layercolor = [Cclayercolor layerwithcolor: Color];//added to the scene [scene Addchild:layercolor];
:


4, Cclayergradient

Cclayergradient is a subclass of Cclayercolor,

you can set gradient colors for a layer

Red: #ffff0000ccColor4B red = ccc4 (255, 0, 0, 255);//blue: #ff0000ffccColor4B blue = ccc4 (0, 0, 255, 255);//Initialize a gradient layer, from red fade Change to blue cclayergradient *layergradient = [cclayergradient layerwithcolor:red fadingto:blue];//added to scene [scene AddChild: Layergradient];
:


5, Cclayermultiplex

Cclayermultiplex inherits from Cclayer, called "multiple layers."

It can contain multiple Cclayer objects,

But at any moment only one cclayer can be active ,

by SwitchTo: and Switchtoandreleaseme: Method

you can make a layer active,

The difference is Switchtoandreleaseme: Method

The layer that is currently active is released first.

Make the required layer in the parameter active again

Create 2 layers Cclayer *layer1 = [Cclayer node]; Cclayer *layer2 = [Cclayer node];//creates a multiple layer that contains layer1 and layer2, but only one of the layers can be displayed at a time cclayermultiplex *plex = [ Cclayermultiplex Layerwithlayers:layer1, Layer2, nil];//let Layer1 be active (Layer2 still in memory) [Plex switchto:0];// Make Layer2 active (Layer1 is still in memory) [Plex switchto:1];//releases the currently active layer2 (Layer2 is removed from memory) and then makes Layer1 active [plex Switchtoandreleaseme:0];<span style= "FONT-SIZE:18PX;" > </span>

Transitions between layers do not have a transition effect




Ios_31_cocos2d_ Layer Cclayer_ Accelerometer

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.