前面說到可以使用CCReader的幾個方法來控制CCB files,今天就我們來實作這些方法,讓PlayGameScene的Hero,能隨著我們的指尖的位置移動。
首先先用SpriteBuilder開啟_[Day16] SpriteBuilder換圖動畫實作_的專案。
重新編輯Hero.ccb動畫名稱。
將GamePlayScene中的Hero移除並發佈至Xcode專案中。
GamePlayScene.m程式碼如下:
#import "GamePlayScene.h"
@interface GamePlayScene ()
@property (strong, nonatomic) CCSprite *hero;
@end
@implementation GamePlayScene
- (void)back {
// 透過CCBReader讀取CCB files
CCScene *gamePlayScene = [CCBReader loadAsScene:@"MainScene"];
[[CCDirector sharedDirector] replaceScene:gamePlayScene];
}
- (void)didLoadFromCCB {
self.userInteractionEnabled = YES;
self.hero = (CCSprite *)[CCBReader load:@"Hero"];
self.hero.position = ccp(200, 150);
self.hero.scale = 3.0f;
[self addChild:self.hero];
}
- (void)touchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
}
- (void)touchMoved:(UITouch *)touch withEvent:(UIEvent *)event {
[self.hero.animationManager runAnimationsForSequenceNamed:@"HeroAnimation"];
CGPoint touchLoc = [touch locationInNode:self];
self.hero.position = touchLoc;
}
- (void)touchEnded:(UITouch *)touch withEvent:(UIEvent *)event {
}
@end
程式方法解釋:
當CCB files載入完畢後。
- (void)didLoadFromCCB {
}
讀取Hero.ccb並且加入至場景之中。
self.hero = (CCSprite *)[CCBReader load:@"Hero"];
self.hero.position = ccp(200, 150);
self.hero.scale = 3.0f;
[self addChild:self.hero];
開啟場景上的touch事件。
self.userInteractionEnabled = YES;
截取場景上的touch事件。
- (void)touchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
}
- (void)touchMoved:(UITouch *)touch withEvent:(UIEvent *)event {
}
- (void)touchEnded:(UITouch *)touch withEvent:(UIEvent *)event {
}
當點擊移動後,執行HeroAnimation動畫,並且改變hero的坐標,讓hero跟著手指移動。
- (void)touchMoved:(UITouch *)touch withEvent:(UIEvent *)event {
[self.hero.animationManager runAnimationsForSequenceNamed:@"HeroAnimation"];
CGPoint touchLoc = [touch locationInNode:self];
self.hero.position = touchLoc;
}
透過CCBReader幾個方法,讓我們能獲取CCB files並且轉換為我們想要的物件。
現在,是不是跟筆者一樣,透過CCBReader讓場景中的Hero跟隨著我們的指尖移動呢?