2013年11月28日 星期四

在cocos2d里面如何拖拽精灵

參考網頁 http://www.raywenderlich.com/zh-hans/21318/%E5%9C%A8cocos2d%E9%87%8C%E9%9D%A2%E5%A6%82%E4%BD%95%E6%8B%96%E6%8B%BD%E7%B2%BE%E7%81%B5

以網頁上的說明來測試,由於網頁上的參考例子不是在ios7/xcode5.0上做的,因此無法直接執行,因此就手動修改來測試一下,並將過程記錄一下。

1. 先啟動一個專案,要使用cocos2d_IOS的Template




2. 將Target設定為7.0,這是因為cocos2d V2.1內定為4.0,並且可以把HelloWorld及Intro這兩組檔案刪除,因為我們會重寫兩個新檔案來取代。



3. 開啟一個新的.h檔,設為GameConfig.h,以下是檔案內容


//
// Supported Autorotations:
//        None,
//        UIViewController,
//        CCDirector
//
#define kGameAutorotationNone 0
#define kGameAutorotationCCDirector 1
#define kGameAutorotationUIViewController 2

//
// Define here the type of autorotation that you want for your game
//
#define GAME_AUTOROTATION kGameAutorotationUIViewController

// 設定用來切換是否使用Gesture元件,原始內容沒有
#define USE_Gesture  1



 4.加一組新的HelloWorldScene的檔案,並將下面內容加入。







HelloWorldScene.h

#import "cocos2d.h"

// HelloWorld Layer
@interface HelloWorld : CCLayer
{
    CCSprite * background;
    CCSprite * selSprite;
    NSMutableArray * movableSprites;
}

// returns a Scene that contains the HelloWorld as the only child
+(id) scene;

@end


HelloWorldScene.m

#import "HelloWorldScene.h"

// HelloWorld implementation
@implementation HelloWorld

+(id) scene
{
    // 'scene' is an autorelease object.
    CCScene *scene = [CCScene node];
   
    // 'layer' is an autorelease object.
    HelloWorld *layer = [HelloWorld node];
   
    // add layer as a child to scene
    [scene addChild: layer];
   
    // return the scene
    return scene;
}

// on "init" you need to initialize your instance
-(id) init {
    if((self = [super init])) {       
        CGSize winSize = [CCDirector sharedDirector].winSize;
       
        [CCTexture2D setDefaultAlphaPixelFormat:kCCTexture2DPixelFormat_RGB565];
        background = [CCSprite spriteWithFile:@"blue-shooting-stars.png"];
        background.anchorPoint = ccp(0,0);
        background.scale = 2.0; // 原圖太小了,放大
        [self addChild:background];
        [CCTexture2D setDefaultAlphaPixelFormat:kCCTexture2DPixelFormat_Default];
       
        movableSprites = [[NSMutableArray alloc] init];
        NSArray *images = [NSArray arrayWithObjects:@"bird.png", @"cat.png", @"dog.png", @"turtle.png", nil];      
        for(int i = 0; i < images.count; ++i) {
            NSString *image = [images objectAtIndex:i];
            CCSprite *sprite = [CCSprite spriteWithFile:image];
            float offsetFraction = ((float)(i+1))/(images.count+1);
            sprite.position = ccp(winSize.width*offsetFraction, winSize.height/2);
            sprite.scale = 2.0;
            [self addChild:sprite];
            [movableSprites addObject:sprite];
        }

#ifndef  USE_Gesture
        [[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];
#endif
    }
    return self;
}

// on "dealloc" you need to release all your retained objects
- (void) dealloc
{
    [movableSprites release];
    movableSprites = nil;
    [super dealloc];
}

- (void)selectSpriteForTouch:(CGPoint)touchLocation {
    CCSprite * newSprite = nil;
    for (CCSprite *sprite in movableSprites) {
        if (CGRectContainsPoint(sprite.boundingBox, touchLocation)) {           
            newSprite = sprite;
            break;
        }
    }   
    if (newSprite != selSprite) {
        [selSprite stopAllActions];
        [selSprite runAction:[CCRotateTo actionWithDuration:0.1 angle:0]];
        CCRotateTo * rotLeft = [CCRotateBy actionWithDuration:0.1 angle:-4.0];
        CCRotateTo * rotCenter = [CCRotateBy actionWithDuration:0.1 angle:0.0];
        CCRotateTo * rotRight = [CCRotateBy actionWithDuration:0.1 angle:4.0];
        CCSequence * rotSeq = [CCSequence actions:rotLeft, rotCenter, rotRight, rotCenter, nil];
        [newSprite runAction:[CCRepeatForever actionWithAction:rotSeq]]; // 擺動
        selSprite = newSprite;
    }
}

- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {   
    CGPoint touchLocation = [self convertTouchToNodeSpace:touch];
    [self selectSpriteForTouch:touchLocation];     
    return TRUE;   
}

- (CGPoint)boundLayerPos:(CGPoint)newPos {
    CGSize winSize = [CCDirector sharedDirector].winSize;
    CGPoint retval = newPos;
    retval.x = MIN(retval.x, 0);
    retval.x = MAX(retval.x, -background.contentSize.width+winSize.width);
    retval.y = self.position.y;
    return retval;
}

- (void)panForTranslation:(CGPoint)translation {   
    if (selSprite) {
        CGPoint newPos = ccpAdd(selSprite.position, translation);
        selSprite.position = newPos;
    } else {
        CGPoint newPos = ccpAdd(self.position, translation);
        self.position = [self boundLayerPos:newPos];     
    } 
}

- (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event {      
    CGPoint touchLocation = [self convertTouchToNodeSpace:touch];
   
    CGPoint oldTouchLocation = [touch previousLocationInView:touch.view];
    oldTouchLocation = [[CCDirector sharedDirector] convertToGL:oldTouchLocation];
    oldTouchLocation = [self convertToNodeSpace:oldTouchLocation];
   
    CGPoint translation = ccpSub(touchLocation, oldTouchLocation);   
    [self panForTranslation:translation];   
}

- (void)handlePanFrom:(UIPanGestureRecognizer *)recognizer {
   
    if (recognizer.state == UIGestureRecognizerStateBegan) {   
       
        CGPoint touchLocation = [recognizer locationInView:recognizer.view];
        touchLocation = [[CCDirector sharedDirector] convertToGL:touchLocation];
        touchLocation = [self convertToNodeSpace:touchLocation];               
        [self selectSpriteForTouch:touchLocation];
       
    } else if (recognizer.state == UIGestureRecognizerStateChanged) {   
       
        CGPoint translation = [recognizer translationInView:recognizer.view];
        translation = ccp(translation.x, -translation.y);
        [self panForTranslation:translation];
        [recognizer setTranslation:CGPointZero inView:recognizer.view];   
       
    } else if (recognizer.state == UIGestureRecognizerStateEnded) {
       
        if (!selSprite) {        
            float scrollDuration = 0.2;
            CGPoint velocity = [recognizer velocityInView:recognizer.view];
            CGPoint newPos = ccpAdd(self.position, ccpMult(velocity, scrollDuration));
            newPos = [self boundLayerPos:newPos];
            [self stopAllActions];
            CCMoveTo *moveTo = [CCMoveTo actionWithDuration:scrollDuration position:newPos];           
            [self runAction:[CCEaseOut actionWithAction:moveTo rate:1]];           
        }       
       
    }       
}

@end


5. 修改AppDelegate.h


#import <UIKit/UIKit.h>
#import "cocos2d.h"

// Added only for iOS 6 support
@interface MyNavigationController : UINavigationController <CCDirectorDelegate>
@end

@interface AppController : NSObject <UIApplicationDelegate>
{
    UIWindow *window_;
    MyNavigationController *navController_;

    CCDirectorIOS    *director_;                            // weak ref
  
    CCScene *winScene;
}

@property (nonatomic, retain) UIWindow *window;
@property (readonly) MyNavigationController *navController;
@property (readonly) CCDirectorIOS *director;
@property (nonatomic, assign)  CCScene  *winScene;

@end


6. 修改AppDelegate.m

#import "cocos2d.h"

#import "AppDelegate.h"
//#import "IntroLayer.h"

#import "HelloWorldScene.h"
#import "GameConfig.h"


@implementation MyNavigationController

// The available orientations should be defined in the Info.plist file.
// And in iOS 6+ only, you can override it in the Root View controller in the "supportedInterfaceOrientations" method.
// Only valid for iOS 6+. NOT VALID for iOS 4 / 5.
-(NSUInteger)supportedInterfaceOrientations {
   
    // iPhone only
    if( [[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone )
        return UIInterfaceOrientationMaskLandscape;
   
    // iPad only
    return UIInterfaceOrientationMaskLandscape;
}

// Supported orientations. Customize it for your own needs
// Only valid on iOS 4 / 5. NOT VALID for iOS 6.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // iPhone only
    if( [[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone )
        return UIInterfaceOrientationIsLandscape(interfaceOrientation);
   
    // iPad only
    // iPhone only
    return UIInterfaceOrientationIsLandscape(interfaceOrientation);
}

// This is needed for iOS4 and iOS5 in order to ensure
// that the 1st scene has the correct dimensions
// This is not needed on iOS6 and could be added to the application:didFinish...
-(void) directorDidReshapeProjection:(CCDirector*)director
{
    if(director.runningScene == nil) {
        // Add the first scene to the stack. The director will draw it immediately into the framebuffer. (Animation is started automatically when the view is displayed.)
        // and add the scene to the stack. The director will run it when it automatically when the view is displayed.
        //[director runWithScene: [IntroLayer scene]];
       
        // Run the intro Scene
        CCScene *scene = [HelloWorldScene scene];
       
#ifdef USE_Gesture
       
        HelloWorldScene *layer = (HelloWorldScene *) [scene.children objectAtIndex:0];
       
        UIPanGestureRecognizer *gestureRecognizer = [[[UIPanGestureRecognizer alloc] initWithTarget:layer action:@selector(handlePanFrom:)] autorelease];
        //[viewController.view addGestureRecognizer:gestureRecognizer];
        [self.view addGestureRecognizer:gestureRecognizer];
       
#endif
       
        [[CCDirector sharedDirector] runWithScene:scene];

    }
}
@end


@implementation AppController

@synthesize window=window_, navController=navController_, director=director_;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Create the main window
    window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
   
   
    // CCGLView creation
    // viewWithFrame: size of the OpenGL view. For full screen use [_window bounds]
    //  - Possible values: any CGRect
    // pixelFormat: Format of the render buffer. Use RGBA8 for better color precision (eg: gradients). But it takes more memory and it is slower
    //    - Possible values: kEAGLColorFormatRGBA8, kEAGLColorFormatRGB565
    // depthFormat: Use stencil if you plan to use CCClippingNode. Use Depth if you plan to use 3D effects, like CCCamera or CCNode#vertexZ
    //  - Possible values: 0, GL_DEPTH_COMPONENT24_OES, GL_DEPTH24_STENCIL8_OES
    // sharegroup: OpenGL sharegroup. Useful if you want to share the same OpenGL context between different threads
    //  - Possible values: nil, or any valid EAGLSharegroup group
    // multiSampling: Whether or not to enable multisampling
    //  - Possible values: YES, NO
    // numberOfSamples: Only valid if multisampling is enabled
    //  - Possible values: 0 to glGetIntegerv(GL_MAX_SAMPLES_APPLE)
    CCGLView *glView = [CCGLView viewWithFrame:[window_ bounds]
                                   pixelFormat:kEAGLColorFormatRGB565
                                   depthFormat:0
                            preserveBackbuffer:NO
                                    sharegroup:nil
                                 multiSampling:NO
                               numberOfSamples:0];
   
    director_ = (CCDirectorIOS*) [CCDirector sharedDirector];
   
    director_.wantsFullScreenLayout = YES;
   
    // Display FSP and SPF
    [director_ setDisplayStats:YES];
   
    // set FPS at 60
    [director_ setAnimationInterval:1.0/60];
   
    // attach the openglView to the director
    [director_ setView:glView];
   
    // 2D projection
    [director_ setProjection:kCCDirectorProjection2D];
    //    [director setProjection:kCCDirectorProjection3D];
   
    // Enables High Res mode (Retina Display) on iPhone 4 and maintains low res on all other devices
    if( ! [director_ enableRetinaDisplay:YES] )
        CCLOG(@"Retina Display Not supported");
   
    // Default texture format for PNG/BMP/TIFF/JPEG/GIF images
    // It can be RGBA8888, RGBA4444, RGB5_A1, RGB565
    // You can change this setting at any time.
    [CCTexture2D setDefaultAlphaPixelFormat:kCCTexture2DPixelFormat_RGBA8888];
   
    // If the 1st suffix is not found and if fallback is enabled then fallback suffixes are going to searched. If none is found, it will try with the name without suffix.
    // On iPad HD  : "-ipadhd", "-ipad",  "-hd"
    // On iPad     : "-ipad", "-hd"
    // On iPhone HD: "-hd"
    CCFileUtils *sharedFileUtils = [CCFileUtils sharedFileUtils];
    [sharedFileUtils setEnableFallbackSuffixes:NO];                // Default: NO. No fallback suffixes are going to be used
    [sharedFileUtils setiPhoneRetinaDisplaySuffix:@"-hd"];        // Default on iPhone RetinaDisplay is "-hd"
    [sharedFileUtils setiPadSuffix:@"-ipad"];                    // Default on iPad is "ipad"
    [sharedFileUtils setiPadRetinaDisplaySuffix:@"-ipadhd"];    // Default on iPad RetinaDisplay is "-ipadhd"
   
    // Assume that PVR images have premultiplied alpha
    [CCTexture2D PVRImagesHavePremultipliedAlpha:YES];
   
    // Create a Navigation Controller with the Director
    navController_ = [[MyNavigationController alloc] initWithRootViewController:director_];
    navController_.navigationBarHidden = YES;

    // for rotation and other messages
    [director_ setDelegate:navController_];
   
    // set the Navigation Controller as the root view controller
    [window_ setRootViewController:navController_];
   
    // make main window visible
    [window_ makeKeyAndVisible];
   
    return YES;
}

// getting a call, pause the game
-(void) applicationWillResignActive:(UIApplication *)application
{
    if( [navController_ visibleViewController] == director_ )
        [director_ pause];
}

// call got rejected
-(void) applicationDidBecomeActive:(UIApplication *)application
{
    [[CCDirector sharedDirector] setNextDeltaTimeZero:YES];   
    if( [navController_ visibleViewController] == director_ )
        [director_ resume];
}

-(void) applicationDidEnterBackground:(UIApplication*)application
{
    if( [navController_ visibleViewController] == director_ )
        [director_ stopAnimation];
}

-(void) applicationWillEnterForeground:(UIApplication*)application
{
    if( [navController_ visibleViewController] == director_ )
        [director_ startAnimation];
}

// application will be killed
- (void)applicationWillTerminate:(UIApplication *)application
{
    CC_DIRECTOR_END();
}

// purge memory
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application
{
    [[CCDirector sharedDirector] purgeCachedData];
}

// next delta time will be zero
-(void) applicationSignificantTimeChange:(UIApplication *)application
{
    [[CCDirector sharedDirector] setNextDeltaTimeZero:YES];
}

- (void) dealloc
{
    [window_ release];
    [navController_ release];
   
    [super dealloc];
}
@end


7. 將圖黨下載後,加入專案中,以下是檔案列表



 8. 完成以上程序後就可以執行了,在config中可以切換兩種不同的拖拽模式,一種是使用UIView的原件,一種是使用cocos2d的內部辨識模式。因為原圖形是在iphone3中執行,所以圖片都太小了。原始文件中,背景圖的拖拽,原本就有問題,因不需要使用,就不修改了。

因此將圖稍稍放大兩倍來用,執行結果如下。




沒有留言: