下面是根据颜色和其他一些属性来处理创建球的方法。createBall 方法返回一个 CCPhysicsSprite。numberOfBallsToCreate 返回每种颜色中的一种,但黑色返回五种。
-(void)ballCreation:(b2World*)world inLayer:(CCLayer*)layer {
CGSize s = [[CCDirector sharedDirector] winSize];
ballType = blackBall;
for (int i = 0; i < [self numberOfBallsToCreate]; i++) {
switch (ballType) {
case greenBall:
[self createBall:world inLayer:layer atPosition:[self ballPosition] ballImage:@"greenBall.png"];
break;
case redBall:
[self createBall:world inLayer:layer atPosition:[self ballPosition] ballImage:@"redBall.png"];
break;
case blueBall:
[self createBall:world inLayer:layer atPosition:[self ballPosition] ballImage:@"blueBall.png"];
break;
case blackBall:
[blackBallArray addObject:[self createBall:world inLayer:layer atPosition:[self ballBirdPositions] ballImage:@"blackBall.png"] ];
break;
default:
break;
}
}
}
下面还有一种方法,我每 1/60 秒更新一次,对每个球施加力。除黑球外,所有球的更新都运行良好。
-(void)updateBalls {
switch ([self getBallType]) {
case greenBall:
[self applyGreenForce];
break;
case redBall:
[self applyRedForce];
break;
case blueBall:
[self applyBlueForce];
break;
case blackBall: {
//[self applyBlackForce];
createdBlackBallArray = [self getBlackBallArray];
CCLOG(@"the createdBlackBallArray count is %d", createdBlackBallArray.count); // always prints zero
if (createdBlackBallArray != NULL) {
//CCLOG(@"code reached here");
for (int i = 0; i < createdBlackBallArray.count; i++) {
CCPhysicsSprite* blackBallPhysicsSprite = [createdBlackBallArray objectAtIndex:i];
//if (blackBallPhysicsSprite.b2Body != NULL) {
b2Vec2 ballForce = b2Vec2(1.0, 0.5);
blackBallPhysicsSprite.b2Body->ApplyForce(ballForce, blackBallPhysicsSprite.b2Body->GetWorldCenter() );
}
}
}
break;
default:
break;
}
上面的 CCLOG 始终为数组计数提供零,因此不会施加力。我不确定我做错了什么。getBlackBallArray 详细信息如下:
-(NSMutableArray*)getblackBallArray {
return blackBallArray;
}
我该如何解决这个问题?
更新
这是初始化数组的 initWithBall 方法。
-(id)initWithBall:(b2World*)world inLayer:(CCLayer*)layer {
[self ballCreation:world inLayer:layer];
blackBallArray = [[NSMutableArray alloc] init];
createdBlackBallArray = [[NSMutableArray alloc] init];
return self;
}
Ball.h 类的一部分如下:
#import "GameObjects.h"
typedef NS_ENUM(NSUInteger, ballTypes) {
blueBall = 0,
blackBall = 1,
redBall = 2,
greenBall = 3,
};
@interface Ball : CCNode {
b2Body* ballBody;
b2World* ballWorld;
CCLayer* ballLayer;
ballTypes ballType;
NSString* ballImageName;
NSMutableArray* blackBallArray;
NSMutableArray* createdBlackBallArray;
}
-(void)updateBalls;
@end