Ios_31_cocos2d_ Message Dispatch

Source: Internet
Author: User
Tags addchild

Final effect:



Cocos2d V3 as long as the-(void) Update: (cctime) Delta method is implemented,

It will be called automatically without the need to manually call

When foreach or for in is traversed, the member cannot be added or deleted










Encapsulated bullet class, inherited from Ccsprite

  bullet.h//  31_cocos2d Primer////  Created by Beyond on 14-9-7.//  Copyright (c) 2014 Com.beyond. All rights reserved.//  Bullet member properties:  How much speed per second #import "CCSprite.h" @interface bullet:ccsprite//speed (move this speed per second) @ Property (Nonatomic, assign) cgpoint velocity; @end



  bullet.m//  31_cocos2d Primer////  Created by Beyond on 14-9-7.//  Copyright (c) 2014 Com.beyond. All rights reserved.//#import "Bullet.h" @implementation bullet//does nothing in cocos2d v3-(ID) initwithtexture: ( Cctexture *) Texture rect: (cgrect) Rect{<span style= "White-space:pre" ></span>    if (self = [super Initwithtexture:texture Rect:rect]) {        //default call to update:        //[Self Schedule: @selector (update:) interval:0];                        Cancel message dispatch        //[self unschedule:<# (SEL) #>];    }    return self;} Distance = speed * Time//Delta two time between brush frames-(void) Update: (cctime) delta{    //Increment x value per 5/    /self.position = Ccpadd (self.positi On, CCP (5, 0));        s = speed * Time    cgpoint DeltaS = Ccpmult (_velocity, delta);        Change location    self.position = Ccpadd (self.position, DeltaS);} @end


Main scene



  helloworldscene.h//  31_cocos2d Primer////  Created by Beyond on 14-9-5.//  Copyright Com.beyond 2014. All rights reserved.////importing Cocos2d.h and cocos2d-ui.h, would import anything you need to start using cocos2d v3#imp Ort "Cocos2d.h" #import "cocos2d-ui.h"/** *  Home View */@interface helloworldscene:ccscene+ (Helloworldscene *) scene;-( ID) init; @end





helloworldscene.m//31_cocos2d Primer////Created by Beyond on 14-9-5.//Copyright Com.beyond 2014. All rights reserved.//#import "HelloWorldScene.h" #import "IntroScene.h" #import "CCAnimation.h"//Bullets #import "Bullet.h" @implementation helloworldscene{ccsprite *_sprite;} #pragma mark-life cycle + (Helloworldscene *) scene{return [[Self alloc] init];} In Helloworldscene-(ID) init{if (! (        self = [super init]) return (nil);        1, Scene node allows interactive self.userinteractionenabled = YES; 2. Create background color for dark gray ccnodecolor *background = [Ccnodecolor nodewithcolor:[cccolor colorwithred:0.2f green:0.2f blue:0.2f al    PHA:1.0F]];        [Self addchild:background];        3. Add a sprite and center [self addspriteincenter];        4. Top right, create a Back button, click to return to the first scene [self addbtnontopright];        5. Important, open message call//[Self Schedule: @selector (update:) interval:0]; Returns the created scene object return self;        #pragma mark-enter & exit//-(void) onenter{//must always first call the OnEnter method of the parent class [Super OnEnter]; Inch Pre-v3, touch Enable and Scheduleupdate was called here/V3, touch are enabled by setting userinteractionenabled F  or the individual nodes//per frame update is automatically enabled, if update is overridden}-(void) onexit{// The OnExit method of the parent class must always be called last [Super OnExit];} #pragma mark-Touch Event//user touch screen, Sprite follows finger move-(void) Touchbegan: (Uitouch *) Touch withevent: (uievent *) event {Cgpoint Touchloc        = [Touch locationinnode:self];        Output Touch Point coordinates cclog (@ "Move sprite to @%@", Nsstringfromcgpoint (Touchloc));    The moving sprite to the touch point represents an absolute by representation of the relative//ccactionmoveto *actionmove = [Ccactionmoveto actionwithduration:1.0f position:touchloc]; Call the wizard's Runaction method to perform the action//[_sprite Runaction:actionmove];}  Put a bullet on the hand, and let the bullet out, and collision detection-(void) touchended: (Uitouch *) Touch withevent: (uievent *) event{//Get Touch point Cgpoint            Touchloc = [Touch locationinnode:self];    Bullet *bullet = [Bullet spritewithimagenamed:@ "Bullet.png"];    Bullet.name = @ "Bullet"; Set the position where the bullet appears BUllet.position = Touchloc;    Set the speed of the bullet bullet.velocity = CCP (ccrandom_minus1_1 () * 300); [Self addchild:bullet];} In the scene's message dispatch, the collision detection-(void) Update: (cctime) delta{[self boundarycheck];} -(void) boundarycheck{for (int i = 0; i<self.children.count;i++) {Ccsprite *child = [Self.children obje        CTATINDEX:I]; Bullet if ([Child.name isequaltostring:@ "Bullet"]) {//1. Fly to the right//Cgpoi            NT pos = child.position;            Pos.x + = 5;                        Child.position = pos;            2. Collision detection with people//ccsprite *person = (Ccsprite *) [self getchildbyname:@ "Nana" Recursively:yes]; if (Cgrectintersectsrect (Child.boundingbox, _sprite.boundingbox)) {//Remove bullets [ch                ILD Removefromparentandcleanup:yes];                Cclog (@ "met people");                _sprite.opacity = _sprite.opacity*0.8; if (_sprite.opacity < 0.) {_sprite.position = CCP ( -10,-10); }} else if (! Cgrectcontainsrect (Self.boundingbox, Child.boundingbox)) {//Remove bullets [child Removefromparenta                Ndcleanup:yes];            Cclog (@ "Leave the screen"); }}}} #pragma mark-button click Event-(void) onbackclicked: (ID) sender{//Use transition animation to toggle scene to Introscene [[Ccdirector S Hareddirector] Replacescene:[introscene scene] Withtransition:[cctransition transitionpushwi Thdirection:cctransitiondirectionright duration:1.0f]];} #pragma mark-Private method//top right, create a Back button, click, return to the previous scene-(void) addbtnontopright{//5, top right, create a Back button, click to return to the first scene Ccbutton *ba    Ckbutton = [Ccbutton buttonwithtitle:@ "[Back]" fontname:@ "Verdana-bold" fontsize:18.0f];    Backbutton.positiontype = ccpositiontypenormalized;    On the top right of the screen note here is the Cartesian coordinate system, the origin at the lower left backbutton.position = CCP (0.85f, 0.95f); Listen for click events [Backbutton settarget:self selector: @selector (onbackclicked:)]; [Self Addchild:backbutton];} Add a sprite and set the position centered-(void) addspriteincenter{//3, add an elf, and set the position centered colorcircle _sprite = [Ccsprite spritewithimagename    d:@ "Nana_logo.png"];        _sprite.name = @ "Nana";        NSString *fullpath = [[NSBundle mainbundle] pathforresource:@ "Nana_logo.png" oftype:nil];        _sprite = [Ccsprite spritewithtexture:[cctexture Texturewithfile:fullpath] Rect:cgrectmake (0, 0, 112, 112)];    _sprite.position = CCP (SELF.CONTENTSIZE.WIDTH/2,SELF.CONTENTSIZE.HEIGHT/2);        _sprite.position = CCP (SELF.CONTENTSIZE.WIDTH*0.85,SELF.CONTENTSIZE.HEIGHT/2); [Self addchild:_sprite];} Create a rotation action for the sprite-(void) addrotateaction{//4, create a rotation action for the sprite, and call the wizard's Runaction method, repeat the action ccactionrotateby* actionspin = [CC    Actionrotateby actionwithduration:1.5f angle:360]; [_sprite runaction:[ccactionrepeatforever actionwithaction:actionspin];}    Test Sprite Properties-(void) testccsprite{_sprite.opacity = 125;    _sprite.color = [Uicolor redcolor];//ccc3 (255, 0, 0); _sPrite.color = [Cccolor colorwithred:1.0f green:0.2f blue:0.2f alpha:1.0f];    _sprite.flipx = YES;            _sprite.flipy = YES;    Ccaction *action = [Ccactioncallfunc actionwithtarget:self selector: @selector (go:)]; [_sprite runaction:action];} Play frame animation "Zhao Yun"-(void) playframeanimatiton{//Create Sprite and center "remember addchild" _sprite = [Ccsprite spritewithimagenamed:@ "1.png    "];    _sprite.position = CCP (SELF.CONTENTSIZE.WIDTH/2,SELF.CONTENTSIZE.HEIGHT/2);    Used to store all frames nsmutablearray *frames = [Nsmutablearray array]; Load all pictures for (int i = 1; i<=; i++) {//1, stitching picture name nsstring *name = [NSString stringwithformat:@ "%i.        PNG ", I];        2, according to the image name (or full path) to generate texture, a picture corresponding to a texture object cctexture *texture = [Cctexture texturewithfile:name];        CGRect RETCT = CGRectMake (0, 0, texture.contentSize.width, texture.contentSize.height);  3. Create a Sprite frame based on the texture ccspriteframe *frame = [[Ccspriteframe alloc]initwithtexture:texture RECTINPIXELS:RETCT Rotated:NO OFFSET:CCP (0,0) OriginalSize:retct.size];    4. Add the sprite frame to the sprite frame array [frames addobject:frame]; }//Create ccanimation according to "Sprite frame array", Parameters: Play next picture every 0.1 seconds ccanimation *animation = [Ccanimation animationwithspriteframes:frames        delay:0.1];    Create an action based on the Ccanimation object ccactionanimate *animate = [Ccactionanimate actionwithanimation:animation];    Ccactionrepeatforever *forever = [Ccactionrepeatforever actionwithaction:animate];    [_sprite Runaction:forever]; Important ~ ~ ~ must be the child node of the scene [self addchild:_sprite];} @end












Ios_31_cocos2d_ Message Dispatch

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.