IOS_31_cocos2d _ aircraft
Finally:
Texture Material
Scenario
//// GameScene. m // 31_cocos2D getting started /// Created by beyond on 14-9-27. // Copyright (c) 2014 com. beyond. all rights reserved. // lightning, game scenario # import "GameScene. h "# import" Hero. h "// background music // # import" SimpleAudioEngine. h "# import" OALSimpleAudio. h "// bullet genie # import" Pellet. h "// Enemy machine # import" Enemy. h "// maximum number of bullets initialized at a time # define kPelletMaxCount 10 // The total interval between the two bullets # define kPelletTotalIntervalTime 0.3 // maximum number of enemy planes # define kEnemy MaxCount 5 @ interface GameScene () {// because a spriteBatchNode corresponds to a texture (image), the genie (frames) cropped from the texture album are all handed over to spriteBatchNode for unified management, in this scenario, you only need to deal with spriteBatchNode * _ batch; // The Background 2 image is always above the head of the Background 1 image. The CCSprite * _ bg1, * _ bg2; // hero, hero * _ hero; // mark whether BOOL _ isGameRuning is running; // important ~~~~ Bullet cache NSMutableArray * _ pelletArr; // The member variable is used to remember the accumulated interval. When it reaches a certain amount (for example, 0.3 seconds ), the total interval (cumulative) between the first bullet and the second bullet occurrence. CGFloat _ pelletTotalIntervalTime; // important ~~~~ Enemy cache NSMutableArray * _ enemyArr;} @ end @ implementation GameScene # pragma mark-Override parent class method-(id) init {if (self = [super init]) {// 1. basic initialization [self setupBasic]; // 2. initialize the background // initialize the background and add it to batchNode for unified management. In the clock method, scroll to the background [self setupBg]; // 3. initialize the hero // initialize the hero and add it to batchNode for unified management. In the clock method, the collision detection [self setupPlayer]; // 4. initialize bullets // initialize a specified number of bullets and add them to batchNode for unified management. In the clock method, the bullets are shot [self setupPelletArr]; // 5. initialize the enemy machine [self setupEnemyArr]; // 6. start the game [self startGame];} return self;} # pragma mark-initialization # pragma mark 1. basic initialization-(void) setupBasic {// 1. load the texture album to the sprite frame cache [[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile: @ "gameArts. plist "]; // 2. create a sprite batchNodeWithFile = [CCSpriteBatchNode batchNodeWithFile: @ "gameArts.png"]; [self addChild: _ batch]; // 3. add a button to pause or resume the game [self setupPauseButton];} // 4. add a button to pause or resume the game-(void) setupPauseButton {// call the method encapsulated by the parent class. Bind the listening method: gameControlBtnClicked [self addBtn: @ "Pause/continue" position: ccp (0.5, 0.5) target: self sel: @ selector (gameControlBtnClicked)];} # pragma mark 2. initialize background-(void) setupBg {NSString * bgPicName = @ "background_2.png"; _ bg1 = [CCSprite spriteWithImageNamed: bgPicName]; _ bg1.anchorPoint = CGPointZero; // The Background 2 image is always above the head of the Background 1 image _ bg2 = [CCSprite spriteWithImageNamed: bgPicName]; _ bg2.anchorPoint = CGPointZero; [_ batch addChild: _ bg1]; [_ batch addChild: _ bg2] ;}# pragma mark 3. initialize the player-(void) setupPlayer {_ hero = [Hero node]; // because it is cropped from the same large Texture Based on the key, it can be added to the same genie batchNode, it centrally manages [_ batch addChild: _ hero] ;}# pragma mark 4. initialize the bullet cache // initialize a specified number of bullets and add them to the batchNode for unified management. In the clock method, issue a bullet-(void) setupPelletArr {_ pelletArr = [NSMutableArray array]; // initialize a specified number of bullets and add them to batchNode for unified management. In the clock method, shot bullet for (int I = 0; I
= KPelletTotalIntervalTime) {Pellet * pellet; for (pellet in _ pelletArr) {// if there are bullets invisible in the array, they are displayed outside the screen; therefore, they can be recycled for reuse; you only need to re-adjust the position to launch if (pellet. visible = NO) {CGPoint from = ccp (_ hero. position. x, CGRectGetMaxY (_ hero. boundingBox); [pellet emitFrom: from velocity: ccp (0,200)]; break;} // if no usable array .... after traversing, you can only create a new one. (remember to add it to the array ~) Pellet = nil;} // if there is no usable... in the array .... after traversing, you can only create a new launch. (remember to add it to the array ~) // There is no reusable bullet if (pellet = nil) {// actually, it has been encapsulated internally, and the new bullet created by default is invisible, pellet * p = [Pellet node] is visible only when emit is launched; // large bullet p. type = kPelletTypeBig; // important ~~~ Be sure, remember to add it to the array [_ pelletArr addObject: p]; // Add it to the sprite batchNode [_ batch addChild: p]; // new bullet shot CGPoint from = ccp (_ hero. position. x, CGRectGetMaxY (_ hero. boundingBox); [p emitFrom: from velocity: ccp (0,200)];} // member variable used for record, zeroes _ pelletTotalIntervalTime = 0 ;}# pragma mark 3. battle of Enemy planes-(void) enemyAnimation :( CCTime) delta {enemy * enemy; for (Enemy in _ enemyArr) {// If the array contains any enemy planes invisible, the description is outside the screen. Therefore, it can be recycled and used cyclically. You only need to adjust the position to participate in the battlefield I F (enemy. visible = NO) {// internally decide on how to exercise [enemy attendTheBattle]; // send a break to the battlefield at a clock cycle ;}}} # pragma mark collision \ Boundary Detection-(void) collsionAndBoundaryCheck {// bullet detection Pellet * pellet; for (pellet in _ pelletArr) {// visible only within the screen range, collision Detection is required. if not visible, analyze the next bullet if (pellet. visible = NO) continue; // 1. bullet and screen detection // 2. bullet and enemy detection [self checkPellet: pellet];} // traverse the end Of the bullet cache array} // 1. bullet and screen detection // 2. bullet and enemy plane detection-(void) c HeckPellet :( Pellet *) pellet {// intersection detection of bullet border and screen border if (! CGRectIntersectsRect (self. boundingBox, pellet. boundingBox) {// 1. after leaving the screen (no intersection), the bullet disappears [pellet dismiss];} else {// 2. the bullet is still on the screen. Collision Detection with the Enemy/enemy * Enemy; for (enemy in _ enemyArr) {// if not visible, no need to detect // only visible within the screen range, collision detection is required; if not visible, directly analyze the next if (enemy. visible = NO) continue; // 1. enemy machine and screen rect detection // 2. enemy plane and bullet detection // 3. enemy and hero detection [self enemy: enemy checkWithPellet: pellet];} // traverses the bullet cache array to end} // Collision Detection of bullets and enemies }// 1. enemy machine and screen rect detection // 2. enemy plane and bullet detection // 3. enemy and hero detection-(void) Enemy :( enemy *) enemy checkWithPellet :( Pellet *) pellet {// intersection detection of Enemy and screen rect borders if (! CGRectIntersectsRect (self. boundingBox, enemy. boundingBox) {// if there is no intersection, it indicates that the enemy machine has escaped from the screen range, so the enemy machine is hidden; [enemy hide];} else if (CGRectIntersectsRect (pellet. boundingBox, enemy. boundingBox) {// intersection detection with (on-screen) bullets is required only for enemy planes within the screen range. // first, hide the [pellet dismiss] Bullet; // then, the [enemy gotHit];} else {// custom method is displayed. the intersection between the hero and the enemy is detected in [self enemyCheckWithHero: enemy]; }}// custom method, intersection detection of heroes and enemies-(void) enemyCheckWithHero :( Enemy *) enemy {// although the bullet did not hit, but the hero collided with the Enemy, game over if (CGRectContainsRect (_ hero. boundingBox, enemy. boundingBox) {[_ hero dieWithEnemyTogether]; // game over, end game [self endGame] ;}# pragma mark-touch event // touch an is required, otherwise, you cannot respond-(void) touchBegan :( UITouch *) touch withEvent :( UIEvent *) event {}-(void) touchMoved :( UITouch *) touch withEvent :( UIEvent *) event {// 1. current point CGPoint curPoint = [[CCDirector shareddire] convertToGL: [touch locationInView: touch. view]; // 2. previous vertex CGPoint prePoint = [[CCDirector shareddire] convertToGL: [touch previuslocationinview: touch. view]; // 3. set the location of the aircraft CGPoint newPosition = ccpAdd (_ hero. position, ccpSub (curPoint, prePoint); // 4. during dragging, the boundary is detected and the CGFloat _ heroWidth = _ hero cannot be displayed. contentSize. width; CGFloat _ heroHeight = _ hero. contentSize. height; if (newPosition. x <_ heroWidth * 0.5) {return;} else if (newPosition. x> self. contentSize. width-_ heroWidth * 0.5) {return;} else if (newPosition. y <0) {return;} else if (newPosition. y> self. contentSize. height-_ heroHeight) {return;} _ hero. position = newPosition;} @ end
Bullet Pellet
//// Pellet. h // 31_cocos2D getting started /// Created by beyond on 14-9-28. // Copyright (c) 2014 com. beyond. all rights reserved. // # import "CCSprite. h "typedef enum {// small bullet kPelletTypeSmall, // large bullet kPelletTypeBig} PelletType; @ interface Pellet: CCSprite // bullet type @ property (nonatomic, assign) PelletType type; // bullet speed (Y direction, and X direction) @ property (nonatomic, assign) CGPoint velocity; // launch emit, parameter: the velocity of the injection point-(void) emitFrom :( CGPoint) from velocity :( CGPoint) velocity; // disappear/hide-(void) dismiss; @ end
//// Pellet. m // 31_cocos2D getting started /// Created by beyond on 14-9-28. // Copyright (c) 2014 com. beyond. all rights reserved. // # import "Pellet. h "// # import" cocos2d is used for Sprite frames. h "// sound effect // # import" SimpleAudioEngine. h "# import" OALSimpleAudio. h "@ implementation Pellet # pragma mark-parent class method-(id) init {if (self = [super init]) {// hidden by default when a bullet is created, self is displayed only when the emit method is called. visible = NO;} return self;} # pragma mark-intercept setter-(void) SetType :( PelletType) type {_ type = type; // Replace the NSString * imgName = _ type = kPelletTypeSmall? @ "Bullet1.png": @ "bullet2.png"; CCSpriteFrame * frame = [CCSpriteFrame frameWithImageNamed: imgName]; [self setSpriteFrame: frame];} # pragma mark-for external calls // launch emit, parameter: the velocity of the point to be shot-(void) emitFrom :( CGPoint) from velocity :( CGPoint) velocity {self. visible = YES; // set the position self. position = from; // set the speed self. velocity = velocity; // sound playback // [[SimpleAudioEngine sharedEngine] playEffect: @ "pelletask"]; [[OALSimple Audio sharedInstance] playEffect: @ "bulletask"];} // disappear/hide-(void) dismiss {self. visible = NO; [self unscheduleAllSelectors];} # pragma mark-clock method (flight)-(void) update :( CCTime) delta {// when the bullet disappears, no longer update position... if (! Self. visible) {return;} // within the deltaTime time, move (flight) a certain distance // distance s = speed v * time t CGPoint s = ccpMult (self. velocity, delta); self. position = ccpAdd (self. position, s) ;}@ end
Hero
//// Hero. h // 31_cocos2D getting started /// Created by beyond on 14-9-27. // Copyright (c) 2014 com. beyond. all rights reserved. // # import "CCSprite. h "@ interface Hero: CCSprite // simple processing. The result of the collision between yingxiong and the enemy is still: game over-(void) dieWithEnemyTogether; @ end
//// Hero. m // 31_cocos2D getting started /// Created by beyond on 14-9-27. // Copyright (c) 2014 com. beyond. all rights reserved. // The main character, representing the player's Hero # import "Hero. h "# import" cocos2d. h "# import" CCDirector. h "# import" CCAnimation. h "@ implementation Hero // initialize the player (airplane)-(id) init {// actually, there is no hero_fly_1.png image in the screenshot. It is cached in the frame of the large image and is extracted (cropped) according to the key) small image if (self = [super initWithImageNamed: @ "hero_fly_1.png"]) {// 1. initialization position, bottom, middle self. anchorPoint = ccp (0.5, 0); // The viewSize obtained from the Director is the screen size CGSize fullScreenSize = [[CCDirector shareddire] viewSize]; self. position = ccp (fullScreenSize. width * 0.5, 0); // 2. two spritframe CCSpriteFrameCache * cache = [CCSpriteFrameCache cached]; CCSpriteFrame * frame1 = [cache cached: @ "hero_fly_1.png"]; CCSpriteFrame * frame2 = [cache cached: @ "hero_fly_2.png"]; NSArray * spriteFramesArr = @ [frame1, frame2]; // 3. add an animation CCAnimation * animation = [CCAnimation animation: spriteFramesArr delay: 0.1]; CCActionAnimate * animate = [CCActionAnimate actionWithAnimation: animation]; // 4. play Frame Animation [self runAction: [CCActionRepeatForever actionWithAction: animate];} return self ;}// simple processing. The result is game over-(void) dieWithEnemyTogether {// stop the previous Frame Animation [self stopAllActions]; // directly play the animation NSMutableArray * frames = [NSMutableArray array]; for (int I = 1; I <= 4; I ++) {NSString * name = [NSString stringWithFormat: @ "canonical", I]; CCSpriteFrame * f = [[CCSpriteFrameCache variable] spriteFrameByName: name]; [frames addObject: f];} CCAnimation * animation = [CCAnimation encoding: frames delay: 0.1]; [self runAction: [CCActionAnimate actionWithAnimation: animation];} @ end
Enemy machine Enemy (awaiting divergence)
/// Enemy. h // 31_cocos2D getting started /// Created by beyond on 14-9-28. // Copyright (c) 2014 com. beyond. all rights reserved. // # import "CCSprite. h "// corresponds to five types of image typedef enum {kEnemyType_1 = 1, kEnemyType_2 = 2, kEnemyType_3 = 3, kEnemyType_4 = 4, kEnemyType_5 = 5} EnemyType; @ interface Enemy: CCSprite @ property (nonatomic, assign) EnemyType type; // appears in the game, plays, and joins the battle-(void) attendTheBattle;-(void) hide; // hit-(void) gotHit; @ end
/// Enemy. m // 31_cocos2D getting started /// Created by beyond on 14-9-28. // Copyright (c) 2014 com. beyond. all rights reserved. // # import "Enemy. h "# import" cocos2d. h "# import" OALSimpleAudio. h "# import" CCAnimation. h "# import" CCDirector. h "@ interface Enemy () {// maximum life value int _ maxHp; // life value int _ hp ;} @ end @ implementation Enemy # pragma mark-parent class method-(id) init {if (self = [super init]) {// hidden by default when an Enemy machine is created, self is displayed only when a call is called and participates in a battle. Visible = NO;} return self;} # pragma mark-intercept setter method-(void) setType :( EnemyType) type {_ type = type; // depending on the enemy type, set the image displayed by the enemy [self setEnemyImage]; // set the maximum enemy life value switch (type) {case kEnemyType_1: _ maxHp = 1; break; case kEnemyType_2: _ maxHp = 2; break; case kEnemyType_3: _ maxHp = 3; break; case kEnemyType_4: _ maxHp = 4; break; case kEnemyType_5: _ maxHp = 5; break; default: break ;}# pragma m Ark-clock method-(void) update :( CCTime) delta {// same as other bullets and heroes, only when displayed, you need to update the location. // when the enemy is invisible, it means it is killed or escaped from the screen. Therefore, you do not need to update its location if (! Self. visible) {return;} // constantly adjust the enemy's position (the speed can be the same as the maximum life value, set different ...) self. position = ccpAdd (self. position, ccp (0,-100 * delta) ;}# pragma mark-for external calls // appears in the game, plays, joins the battle-(void) attendTheBattle {// when the scene is displayed, full blood _ hp = _ maxHp; // when the scene is displayed, self is displayed. visible = YES; // position at the time of appearance, from the top of the screen to dive down self. anchorPoint = ccp (0.5, 0); CGSize winSize = [CCDirector shareddire]. viewSize; // important ~~~ This is because... when the screen is displayed, let it step into the screen with one foot, there is an intersection with the screen window rect self. position = ccp (winSize. width * CCRANDOM_0_1 (), winSize. height-1); // Boundary Detection} // void gotHit {_ hp --; if (_ hp = 0) {// 1. play the corresponding audio effect [self playHitSound]; // 2. play the corresponding exploded animation [self playExplodeAnimation] ;}}// disappear-(void) hide {self. visible = NO; [self unscheduleAllSelectors] ;}# pragma mark-extraction method // set the image displayed by the enemy based on the type of the enemy-(void) setEnemyImage {// depending on the enemy type, set the NSString * name = [NSString stringWithFormat: @ "enemyd_d_fly_1.png", _ type]; // extract the sprite frame from the sprite frame cache and set it to the sprite, show CCSpriteFrame * frame = [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName: name]; [self setSpriteFrame: frame];} // The audio effect (void) for playing) playHitSound {[[OALSimpleAudio sharedInstance] playEffect: [NSString stringWithFormat: @ "enemyuncd_downyun", _ type];} // play an animation explosion, finish explosion, hide, finally, reset the display image to prepare for the next battle-(void) playExplodeAnimation {NSMutableArray * frames = [NSMutableArray array]; // The explosion effect 4 should be dynamically changed .... for (int I = 1; I <= 4; I ++) {NSString * name = [NSString stringWithFormat: @ "enemy1_blowup_0000d.png", I]; CCSpriteFrame * f = [[CCSpriteFrameCache failed] spriteFrameByName: name]; [frames addObject: f];} // noun, animation CCAnimation * animation = [CCAnimation failed: frames delay: 0.1]; // action _ 1 explosion CCActionAnimate * explosion = [CCActionAnimate actionWithAnimation: animation]; // action _ 2 invisible CCActionHide * hide = [CCActionHide action]; // Action _ 3 after the explosion, the sprite's display image has changed, so you need to reset it back so that you can participate in the next battle CCActionCallFunc * func = [CCActionCallFunc actionWithTarget: self selector: @ selector (setEnemyImage)]; // Action _ 4 Use sequence to encapsulate CCActionSequence * sequence = [CCActionSequence actions: explosion, hide, func, nil]; // execute the action [self runAction: sequence];} @ end