第一次用2cocosd编写一个小游戏——DoodleDrop

来源:互联网 发布:最大公约数 c语言 编辑:程序博客网 时间:2024/06/03 18:24

源代码:

//

//  GameScene.h

//  DoodleDrop

//

//  Created by apple on 13-3-14.

//  Copyright 2013 __MyCompanyName__. All rights reserved.

//


#import <Foundation/Foundation.h>

#import "cocos2d.h"


@interface GameScene : CCLayer 

{

    CCSprite* player;

    CGPoint playerVelocity;

    

    // 添加障碍物

    CCArray* spiders;

    float spiderMoveDuration;

    int numSpidersMoved;

    

    // 标签

    CCLabelTTF* scoreLabel; 

    ccTime totalTime; 

    int score;

}


+(id) scene;


@end






//

//  GameScene.m

//  DoodleDrop

//

//  Created by apple on 13-3-14.

//  Copyright 2013 __MyCompanyName__. All rights reserved.

//


#import "GameScene.h"



@implementation GameScene


+(id) scene

{

    CCScene* scene = [ CCScenenode ];

    CCLayer* layer = [ GameScenenode ];

    [ scene addChild: layer ];

    return scene;

}


// resetSpiders 方法

- (void) resetSpiders

{

    CGSize screenSize = [ [ CCDirector sharedDirector ] winSize ];

    

    // get any spider to get its image width

    CCSprite* tempSpider = [ spiders lastObject ];

    CGSize size = [ tempSpider texture ].contentSize;

    

    int numSpiders = [ spiderscount ];

    for ( int i = 0 ; i < numSpiders ; i++ )

    {

        // put each spider at its designated position outside the screen

        CCSprite* spider = [ spiders objectAtIndex: i ];

        spider.position = CGPointMake( size.width * i + size.width *0.5f , screenSize.height + size.height );

        

        [ spider stopAllActions ];

    }

    

    // 让蜘蛛频繁落下的方法

    // unschedule the selector just in case. if it isn't scheduled it won't do anything.

    [ self unschedule:@selector( spidersUpdate:) ];

    

    // schedule the spiders update logic to run at the given interval.

    [ self schedule:@selector( spidersUpdate:) interval:0.7f ];

    

    // reset the move spiders counter and spider move duration ( affects speed )

    numSpidersMoved = 0;

    spiderMoveDuration = 4.0f;

}


// 控制蜘蛛的运动

- (void) runSpiderMoveSequence: (CCSprite*)spider

{

    // slowly increase the spider speed over time 

    numSpidersMoved++;

    if (numSpidersMoved % 8 ==0 && spiderMoveDuration >2.0f )

    {

        spiderMoveDuration -=0.1f;

    }

    

    // this is the sequence which controls the spiders' movement.

    CGPoint belowScreenPosition = CGPointMake( spider.position.x , - [ spidertexture ].contentSize.height );

    CCMoveTo* move = [ CCMoveTo actionWithDuration:spiderMoveDuration

                                          position: belowScreenPosition ];

    CCCallFuncN* callDidDrop = [ CCCallFuncN actionWithTarget: self

                                                     selector: @selector(spiderDidDrop:) ];

    CCSequence* sequence = [ CCSequence actions: move , callDidDrop , nil ];

    [ spider runAction: sequence ];

}


// 重设蜘蛛位置使之可以从屏幕上方重新落下

- (void) spiderDidDrop: (id) sender

{

    // make sure sender is actually of the right class.

    NSAssert( [ sender isKindOfClass: [ CCSprite class ] ], @"sender is not a CCSprite!" );

    CCSprite* spider = ( CCSprite* )sender;

    

    // move the spider back up outside the top of the screen

    CGPoint pos = spider.position;

    CGSize screenSize = [ [ CCDirector sharedDirector ] winSize ];

    pos.y = screenSize.height + [ spidertexture ].contentSize.height;

    spider.position = pos;

}


// 让蜘蛛频繁落下的方法

- (void) spidersUpdate: (ccTime) delta

{

//    CCLOG( @"999" );

    // try to find a spider which isn't currently moving. 

    for ( int i = 0 ; i < 10 ; i++ )

    {

        int randomSpiderIndex = CCRANDOM_0_1() * [ spiders count ];

//        CCLOG( @"%d" , randomSpiderIndex );

        CCSprite* spider = [ spiders objectAtIndex: randomSpiderIndex ];

        

        // if the spider isn't moving it won't have any running actions.

        if ( [ spider numberOfRunningActions ] ==0 )

        {

            // This is the sequence which controls the spiders' movement 

            [ self runSpiderMoveSequence: spider ];

            

            // only one spider should start moving at a time.

            break;

        }

    }

    

    totalTime += delta;

    int currentTime = (int)totalTime;

    if ( score < currentTime )

    {

        score = currentTime;

        [ scoreLabel setString: [NSString stringWithFormat: @"%d" , score ] ]; 

    }

    

}


//初始化障碍物

- (void) initSpiders

{

    CCLOG( @"蜘蛛" );

    CGSize screenSize = [ [ CCDirector sharedDirector ] winSize ];

    

    // using a temporary spider sprite is the easiest way to get the image's size

    CCSprite* tempSprider = [CCSprite spriteWithFile:@"Ability_Creature_Cursed_01.png" ];


    float imageWidth = [ tempSprider texture ].contentSize.width;

    

    // use as many spiders as can fit next to each other over the whole screen width.

    int numSpiders = screenSize.width / imageWidth;

    

    // initialize the spiders array using alloc.

    spiders = [ [ CCArrayalloc ] initWithCapacity: numSpiders ];

    

    for ( int i = 0 ; i < numSpiders ; i++ )

    {

        CCSprite* spider = [CCSprite spriteWithFile:@"Ability_Creature_Cursed_01.png" ];

        [ self addChild: spiderz: 0 tag:2 ];

        CCLOG( @"%@" ,spiders );

        

        // also add the spider to the spiders array.

        [ spiders addObject: spider ];

    }

    // call the method to reposition all spiders

    [ selfresetSpiders ];

}


-(id) init

{

    if ( ( self = [super init ] ) )

    {

        CCLOG( @"%@: %@",NSStringFromSelector( _cmd ), self );

        

        self.isAccessibilityElement =YES;

        

        player = [CCSprite spriteWithFile:@"Ability_Druid_PredatoryInstincts.png" ];

        [ self addChild:player z: 0tag: 1 ];

        

        CGSize screenSize = [ [ CCDirector sharedDirector ] winSize ];

        float imageHeight = [ player texture ].contentSize.height;

        player.position =CGPointMake( screenSize.width / 2 , imageHeight / 2 );

        

        [ self scheduleUpdate ];

        [ self initSpiders ];

        

        scoreLabel = [CCLabelTTF labelWithString:@"0" fontName:@"Cochin" fontSize:48 ];

        scoreLabel.position =CGPointMake( screenSize.width / 2 , screenSize.height );

        

        // ajust the label's anchorPoint's y position to make it align with the top.

        scoreLabel.anchorPoint =CGPointMake( 0.5f ,1.0f );

        

        // add the score label with z value of -1 so it's drawn below everything else

        [ self addChild:scoreLabel z: -1 ];

    }

    return self;

}


-(void) dealloc

{

    CCLOG(@"%@: %@", NSStringFromSelector(_cmd ) , self );

    

    // 障碍物

    [ spiders release ];

    spiders = nil;

    

    // 标签

    [ scoreLabel release ]; 

    

    //never forget to call [ super dealloc ]

    [ super dealloc ];

}


//加速计输入

- (void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration

{

//    CGPoint pos = player.position;

//    pos.x += acceleration.x * 10;

//    player.position = pos;

    

    // controls how quickly velocity decelerates (lower = quicker to change direction )

    float deceleration = 0.4f;

    // determines how sensitive the accelerometer reacts ( higher = more sensitive )

    float sensitivity = 6.0f;

    // how fast the velocity can be at most 

    float maxVelocity = 100;

    // adjust velocity based on current accelerometer acceleration 

    playerVelocity.x =playerVelocity.x * deceleration + acceleration.x * sensitivity;

    

    // we must limit the maximum velocity of the player sprites , in both directions

    if ( playerVelocity.x > maxVelocity )

    {

        playerVelocity.x = maxVelocity;

    }

    else if ( playerVelocity.x < - maxVelocity )

    {

        playerVelocity.x = - maxVelocity;

    }

}


// 碰撞检测

- (void) checkForCollision

{

    // assumption : both player and spider images are squares.

    float playerImageSize = [ player texture ].contentSize.width;

    float spiderImageSize = [ [ spiders lastObject ] texture ].contentSize.width;

    

    float playerCollisionRadius = playerImageSize *0.4f;

    float spiderCollisionRadius = spiderImageSize *0.4f;

    

    // this collision distance will roughly equal the image shapes.

    float maxCollisionDistance = playerCollisionRadius + spiderCollisionRadius;

    

    int numSpiders = [ spiderscount ];

    for ( int i = 0 ; i < numSpiders ; i++ )

    {

        CCSprite* spider = [ spiders objectAtIndex: i ];

        if ( [ spider numberOfRunningActions ] ==0 )

        {

            // this spider isn't even moving so we can skip checking it.

            continue;

        }

        

        // get the distance between player and spider.

        float actualDistance = ccpDistance( player.position , spider.position );

        // are the two objects closer than allowed?

        if ( actualDistance < maxCollisionDistance )

        {

            // game Over ( just restart the game for now )

            [ self resetSpiders ];

            score = 0;

            totalTime = 0;

            [ scoreLabel setString: [NSString stringWithFormat: @"%d" , score ] ];

            break;

        }

    }

}


- (void) update:(ccTime)delta

{

    // Keep adding up the playerVelocity to the player's position 

    CGPoint pos =player.position;

    pos.x += playerVelocity.x;

    

    // The Player should also be stopped from going outside the screen

    CGSize screenSize = [ [ CCDirector sharedDirector ] winSize ];

    float imageWidthHalved = [ player texture ].contentSize.width *0.5f;

    float leftBorderLimit = imageWidthHalved;

    float rightBorderLimit = screenSize.width - imageWidthHalved;

    

    // preventing the player sprite from moving outside the screen 

    if ( pos.x < leftBorderLimit )

    {

        pos.x = leftBorderLimit;

        playerVelocity = CGPointZero;

    }

    else if ( pos.x > rightBorderLimit )

    {

        pos.x = rightBorderLimit;

        playerVelocity = CGPointZero;

    }

    

    // assigning the modified position back

    player.position = pos;

    

    [ selfcheckForCollision ];

}




@end