Cocos2d genie Tutorial: Part 2

Source: Internet
Author: User

Original article link: http://www.iphonegametutorials.com/2010/09/10/cocos2d-sprite-tutorial-part-2/

In the previous tutorial, we left our lonely dragon in the middle of the screen... However, 90% of animations have not been applied, but we have spent a lot of effort to build them! Sorry! Therefore, we need to make up for this shortcoming in this tutorial. We will add touch control to capture users' input and select an appropriate animation for Dragon playback Based on the direction of users' fingers. You can slide your hands on the screen to direct dragon to move.

 

The complete source code of this tutorial is provided here.

For cocos2d, if you want to use touch control, just tell it directly, as shown below:

 
Self. istouchenabled=Yes;

The above self should be the derived class of cclayer or cclayer, because istouchenabled is defined only in cclayer. If istouchenabled is yes, the registerwithtouchdispatcher method will be called when the onenter method enters. Here we need to overwrite it, because we need to use the targeted touch event. If it is not overwritten, The standarded touch event is used by default.

 
-(Void) Registerwithtouchdispatcher
{
[[Cctouchdispatcher shareddispatcher] addtargeteddelegate: Self priority:0Swallowstouches: Yes];
}

 

Targetedtouchdelegate.
Using this type of delegate has two advantages:

1. You no longer need to process nssets,Cctouchdispatcher does the separation work. You will get a unique uitouch every time you call it.

2. You can activate the touch event. You only need to return yes in the cctouchbegan method. When the touchmove/ended/canceled callback is triggered, the dispatcher class will ensure that uitouch is updated every time. In this way, you don't have to worry about all things when dealing with multi-touch.Cctouchdispatcher is ready for you.

Here we will overwrite "cctouchbegan" and "cctouchended" -- the first method is called when the first touch event starts, and the other is called when the touch event ends. There is also a "cctouchmoved" method, which is called when your hand is always pressed on the screen. This method will be involved later.

 -  (bool) cctouchbegan :( uitouch   *  ) touch withevent :( uievent   *  )   event  {< br>   return   yes; 
}< br> - ( void ) cctouchended :( uitouch * ) touch withevent :( uievent * ) event {< br>
}

So now we have tools and functions. Why not write someCodeWhat about it?

 -  (  Void  ) Cctouchended :( uitouch  *  ) Touch withevent :( uievent  *  )  Event  {
Nslog ( @" Cctouchended " );
Cgpoint touchlocation = [Touch locationinview: [Touch view];
Touchlocation = [[Ccdirector shareddire] converttogl: touchlocation];
Touchlocation = [Self converttonodespace: touchlocation];

Cgpoint movevector = Ccpsub (touchlocation, _ dragon. position );

Float Distancetomove = Ccplength (movevector );
Cgfloat moveangle = Ccptoangle (movevector );
Cgfloat cocosangle = Cc_radians_to_degrees ( - 1 * Moveangle );

Float Dragonvelocity = 480.0 / 3.0 ;
Float Moveduration = Distancetomove / Dragonvelocity;

Cocosangle + = 23 ;
If (Cocosangle < 0 )
Cocosangle + = 360 ;

Int Runanim = ( Int ) (Cocosangle) / 45 );

[_ Dragon stopaction: _ flyaction];
Self. flyaction = [_ Flyactionarray objectatindex: runanim];
[_ Dragon runaction: _ flyaction];

Self. moveaction = [Ccsequence actions:
[Ccmoveto actionwithduration: moveduration position: touchlocation],
Nil
];

[_ Dragon runaction: _ moveaction];
}

The first three lines are standard usage (the current version can be replaced with one sentence, called self convertouchtonodespace. If you are interested, you can viewSource code, Which is the same as the following sentence)

Cgpoint touchlocation=[Touch locationinview: [Touch view];
Touchlocation=[[Ccdirector shareddire] converttogl: touchlocation];
Touchlocation=[Self converttonodespace: touchlocation];

 

The screen coordinates are obtained first (that is, the coordinates of the place where your fingers are pressed), and then converted to OpenGL coordinates. The converttonodespace function converts OpenGL coordinates into cclayer coordinates.

Understanding screen coordinates. OpenGL coordinates and node coordinates are very important.

 Cgpoint movevector  = Ccpsub (touchlocation, _ dragon. position );

Float Distancetomove = Ccplength (movevector );
Cgfloat moveangle = Ccptoangle (movevector );
Cgfloat cocosangle = Cc_radians_to_degrees ( - 1 * Moveangle );

Float Dragonvelocity = 480.0 / 3.0 ;
Float Moveduration = Distancetomove / Dragonvelocity;

Cocosangle + = 23 ;
If (Cocosangle < 0 )
Cocosangle + = 360 ;

Int Runanim = ( Int ) (Cocosangle) / 45 );

 

Therefore, we need to calculate how to rotate Dragon:

    1. Calculates the vector from touch point to Dragon's current position.
    2. Calculate the length of the vector (here the pixel length)
    3. Calculate the Radian of the move Vector
    4. Converts radians to degrees (because cocos2d uses degrees)

To get a uniform moving method without worrying about where dragon is currently on the screen, we set a variable to save the speed constant of Dragon Movement (calculated by distance/time ). Then, divide the length of the move vector by the speed to get the duration required by ccmoveto action)

Here I also made some interesting things-because the obtained degree range is-180 to 180, So I add it to 360, so that there will be no negative number. When I divide this degree by 45, I can get an integer that meets the animation array in the 8 (360/45 = 8) directions I previously defined. That is, an animation is obtained through this integer and then played to Dragon. I also added a 23, because when I click on the east side of Dragon, I don't want it to be 0 ~ 8. I am confused when selecting these 8 animations. By adding this small offset, I can calculate the exact animation index. (For example, if there are 0th animations, we get 0 when the animation ranges from-23 to 23 degrees ). If you are still confused, comment out the code "cocosangle + = 23" and then take a look at what the code has done.

[_ Dragon stopaction: _ flyaction];
Self. flyaction=[_ Flyactionarray objectatindex: runanim];
[_ Dragon runaction: _ flyaction];

Self. moveaction=[Ccsequence actions:
[Ccmoveto actionwithduration: moveduration position: touchlocation],
Nil];

[_ Dragon runaction: _ moveaction];

 

Finally, we stop the previous animation, and then based on the previously calculated result "int runanim = (INT) (cocosangle)/45 ); "to select a new animation for Dragon to run. In this way, when we click on the screen, we can move Dragon in the correct direction and play the correct animation. Part 1 of the tutorial is over here. Please refer to Part 2 of the tutorial!

See the next tutorial!

 

Copyright statement: This article consistsHttp://www.cnblogs.com/andyqueTranslation. You are welcome to share it with me. Please respect the work of the author. Keep this note and the author's blog link when reprinting. Thank you!

 

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.