如何在Cocos2D 1.0 中掩饰一个精灵(二)

前端之家收集整理的这篇文章主要介绍了如何在Cocos2D 1.0 中掩饰一个精灵(二)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

大熊猫猪·侯佩原创或翻译作品.欢迎转载,转载请注明出处.
如果觉得写的不好请告诉我,如果觉得不错请多多支持点赞.谢谢! hopy ;)


让我们开始吧

打开Xcode,从New Project中选择cocos2d模板,点击下一步.命名新项目为MaskedCal,点击下一步,选择目标文件夹,然后点击Create.

接下来下载该项目的资源文件:
http://haosou.xqiju.com/browse.php?u=sDrnThWlVVAzW8rIeQpXWRtJQhNB2ji0W8bJoRwh3eLdkttyzhmu26EpJAMSqFoZxzYzSEBUQg0ePg%3D%3D&b=13

并把解压后的文件夹拖到你的Xcode项目中.确保选中”Copy items into destination group’s folder(if needed)”,然后点击Finish.

让我们从一些爵士乐开始,打开AppDelegate.m并作出如下修改:

// Add to top of file
#import "SimpleAudioEngine.h"

// At end of applicationDidFinishLaunching,replace last line with the following 2 lines:
[[SimpleAudioEngine sharedEngine] playBackgroundMusic:@"TeaRoots.mp3" loop:YES];
[[CCDirector sharedDirector] runWithScene: [HelloWorldLayer sceneWithLastCalendar:0]];

代码首先播放的这些很酷的音乐是Kevin MacLeod制作的,然后调用了一个新的初始化场景,我们下面将会描述.

下一步,打开HelloWorldLayer.h,完成如下修改:

// Add new instance variable
int calendarNum;

// Replace the +(CCScene*) scene declaration at the bottom with the following:
+ (CCScene *) sceneWithLastCalendar:(int)lastCalendar;
- (id)initWithLastCalendar:(int)lastCalendar;

在该场景中,我们将显示一个随机的日历图片(从3张中选一张).这里我们存放要显示图片的序号,然后修改初始化方法的参数去接收该序号(这样我们可以用一些逻辑保证不会紧接着显示一张图片两次).

然后切换至HelloWorldLayer.m,做出如下修改:

// Replace +(CCScene *) scene with the following
+(CCScene *) sceneWithLastCalendar:(int)lastCalendar // new
{
    CCScene *scene = [CCScene node];
    HelloWorldLayer *layer = [[[HelloWorldLayer alloc] 
        initWithLastCalendar:lastCalendar] autorelease]; // new
    [scene addChild: layer];    
    return scene;
}

// Replace init with the following
-(id) initWithLastCalendar:(int)lastCalendar
{
    if( (self=[super init])) {

        CGSize winSize = [CCDirector sharedDirector].winSize;

        do {
            calendarNum = arc4random() % 3 + 1;
        } while (calendarNum == lastCalendar);

        NSString * spriteName = [NSString 
            stringWithFormat:@"Calendar%d.png",calendarNum];

        CCSprite * cal = [CCSprite spriteWithFile:spriteName];

        // BEGINTEMP
        cal.position = ccp(winSize.width/2,winSize.height/2);        
        [self addChild:cal];
        // ENDTEMP

        self.isTouchEnabled = YES;
    }
    return self;
}

// Add new methods
- (void)registerWithTouchDispatcher {
    [[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self 
        priority:0 swallowsTouches:YES];
}

- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
    CCScene *scene = [HelloWorldLayer sceneWithLastCalendar:calendarNum];
    [[CCDirector sharedDirector] replaceScene:
        [CCTransitionJumpZoom transitionWithDuration:1.0 scene:scene]];
    return TRUE;
}

以上仅仅是Cocos2D中随机在屏幕中心显示日历图片的基本代码.它同样包括了一些触摸屏幕时回调的基本逻辑代码,它将会展示出切换场景的弹性效果.

原文链接:https://www.f2er.com/cocos2dx/340754.html

猜你在找的Cocos2d-x相关文章