1
我剛剛開始從一個教程學習Cocos2d。我想隨機飛行'蝙蝠',當我觸摸屏幕上的任何地方時,所有蝙蝠聚集在我的觸摸位置,並且他們又開始隨機飛行。
這裏是我的代碼:ccTouch事件在所有相同的精靈(精靈陣列)
-(id) init
{
if((self=[super init])) {
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"Bat.plist"];
//Bats Array Initialization
bats = [[NSMutableArray alloc] init];
//Add bats using a batch node.
CCSpriteBatchNode *batch1 = [CCSpriteBatchNode batchNodeWithFile:@"Bat.png" capacity:10];
[self addChild:batch1 z:2 tag:TAG_BATS];
//Make them start flying up.
for(int x=0; x<5; x++){
//Create SimpleAnimObject of bat
bat1 = [SimpleAnimObj spriteWithBatchNode:batch1 rect:CGRectMake(0,0,48,48)];
[batch1 addChild:bat1];
[bat1 setPosition:ccp(arc4random()%900+40, arc4random()%600+50)];
[bat1 setScale:0.6f];
float flappingSpeed = [self makeBatFlyUp:bat1];
bat1.velocity = ccp((arc4random()%1000)/500 + 0.2f, 0.1f/flappingSpeed);
[bats addObject:[NSValue valueWithPointer:bat1]];
[bat1 retain];
//Set the bat's direction based on x velocity.
if(bat1.velocity.x > 0){
bat1.flipX = YES;
}
}
self.isTouchEnabled = YES;
[self schedule:@selector(step:)];
}
return self;
}
-(float)makeBatFlyUp:(SimpleAnimObj*)bat {
CCSpriteFrameCache * cache = [CCSpriteFrameCache sharedSpriteFrameCache];
float delay = (float)(arc4random()%5+5)/150;
CCAnimation *animation = [[CCAnimation alloc] initWithName:@"simply_bat_fly" delay:delay];
int num = arc4random()%9+1;
for(int i=1; i<=9; i+=1){
[animation addFrame:[cache spriteFrameByName:[NSString stringWithFormat:@"b%i.tiff",num]]];
num++;
if(num > 9){ num = 1; }
}
[bat stopAllActions];
[bat runAction:[CCRepeatForever actionWithAction: [CCAnimate actionWithAnimation:animation]]];
bat.animationType = BAT_FLYING_UP;
return delay;
}
在觸摸事件:
-(BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event{
CGPoint touchLocation = [touch locationInView:[touch view]];
touchLocation = [[CCDirector sharedDirector] convertToGL:touchLocation];
touchLocation = [self convertToNodeSpace:touchLocation];
float velocityBat = 1024/3.0 ;
CGPoint moveDifference = ccpSub(touchLocation,bat1.position);
float distanceMove = ccpLength(moveDifference);
float moveduration = distanceMove/ velocityBat;
// here i have to use Array but i don't know how to use array to access all same sprites.
self.moveAction = [CCSequence actions:
[CCMoveTo actionWithDuration:moveduration position:touchLocation],
[CCCallFunc actionWithTarget:self selector:@selector(bearMoveEnded)],
nil
];
[bat1 runAction:moveAction];
return YES;
}
蝙蝠是正常飛行,但是當我在屏幕上只觸摸蝙蝠跟着我的觸摸事件別人都保留隨機移動。
任何人都可以幫我嗎?如果我錯過任何事情或者我錯了什麼地方?
謝謝!
我看..首先感謝好友.. !!你能否給我一些想法 - '我如何使用'蝙蝠'陣列來訪問所有的蝙蝠?'任何示例代碼或提示可以是很大的幫助! – iUser
你需要知道你想要解決哪個蝙蝠。然後通過[bats objectAtIndex:0]獲得該蝙蝠(這將返回第一隻蝙蝠)。 – LearnCocos2D
但是我想要所有的蝙蝠(所有蝙蝠都是隨機位置)跟隨我的觸摸位置。我對Cocos2d完全陌生,所以我真的不知道 - 它可能與否?如果是,那麼你可以在編碼方面多指導一下嗎? – iUser