我正在爲iPhone的精靈套件遊戲工作,有一個球員和12個「敵人」。這些敵人中的每一個都是以相同的方式創建的。我在initWithSize方法中用for循環做了這個。Sprite工具包,使多個精靈服從相同的方法
for (int i = 1; i <= 12; i++)
{
[self spawnChargesWithNumber:i];
}
使敵人(spawnChargesWithNumber)的實際方法如下。
- (void)spawnChargesWithNumber:(NSInteger)number
{
self.chargedBall = [[ChargedBall alloc] initWithImageNamed:[NSString stringWithFormat:@"ChargedBall%li", (long)number]];
int minX = self.chargedBall.size.width/2;
int maxX = self.frame.size.width - self.chargedBall.size.width/2;
int rangeX = maxX - minX;
int actualX = (arc4random() % rangeX) + minX;
self.chargedBall.position = CGPointMake(actualX, 568);
self.chargedBall.name = [NSString stringWithFormat:@"chargeNumber%li", (long)number];
self.chargedBall.zPosition = 15;
self.chargedBall.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:13.0f];
self.chargedBall.physicsBody.dynamic = YES;
self.chargedBall.physicsBody.affectedByGravity = NO;
self.chargedBall.physicsBody.mass = 0.1;
[self.map addChild:self.chargedBall];
}
這實際上創造了12個不同的敵人,但只有最後一個實際上是一個chargeBall對象。我有一個名爲ChargedBall的對象,其中有一個.h和.m文件。在.m文件中我有一個方法來更新對象的位置。
在update:currentTime方法中,我調用這個方法來更新球的位置,並且我也在這個方法中檢查與tileMap的碰撞。
-(void)update:(CFTimeInterval)currentTime
{
NSTimeInterval delta = currentTime - self.previousUpdateTime;
if (delta > 0.02)
{
delta = 0.02;
}
self.previousUpdateTime = currentTime;
[self.player update:delta];
[self.chargedBall update:delta];
[self checkForAndResolveCollisionsForPlayer:self.player forLayer:self.walls];
[self checkForAndResolveCollisionsForCharge:self.chargedBall forLayer:self.walls];
[self processUserMotionForUpdate:currentTime];
[self setViewPointCenter:self.player.position];
}
如果我只有一個敵人/ chargeBall,這個效果非常好。如果我有多個chargeBalls,那麼只有最後一個的行爲應該如此。其他人只是呆在屏幕上。我認爲這與我如何製作chargeBall有關。我每次重新創建chargedBall對象,以便只有最後一個實際上是一個chargeBall,而不是其他人,因爲我覆蓋了它們。所以我最終的問題是,我如何讓所有敵人/ chargeBall對象的行爲方式相同,並按照相同的方法更新自己?非常感謝您的幫助
非常感謝。這就像一個魅力!而且,我非常喜歡使用makeObjectsPerformSelector的selfDestruct方法:NSArray的方法!再次感謝您的時間和幫助。 – Douglas
沒問題的隊友:) – RaffAl