我对objective-c和iPhone编程非常陌生(虽然,我对C#有更多一点的背景),我是在实践中学习的。
我目前正在尝试做一个迷你平台游戏,而不是自己检查每个平台,看看我的玩家是否与它相交,我想做一个数组和一个for语句来解决这个问题。(如果我错了,请纠正我,但NSMutableArray
看起来很像C#中的List
功能)
我输入了我认为可以工作的东西,但它没有,你知道为什么吗?在我的@interface
中,我有:
@interface ViewController : UIViewController
{
NSMutableArray *platforms;
UIImageView *platform1;
UIImageView *platform2;
UIImageView *platform3;
UIImageView *platform4;
UIImageView *platform5;
UIImageView *player;
}
@property (nonatomic) NSInteger GameState;
@property IBOutlet UIImageView *player;
@property IBOutlet UIImageView *platform1;
@property IBOutlet UIImageView *platform2;
@property IBOutlet UIImageView *platform3;
@property IBOutlet UIImageView *platform4;
@property IBOutlet UIImageView *platform5;
在我的@实现中,我有:
- (void)viewDidLoad
{
[super viewDidLoad];
[NSTimer scheduledTimerWithTimeInterval:1.0/60 target:self selector:@selector(gameLoop) userInfo:nil repeats:YES];
gravity = CGPointMake(0,0.195);
[platforms addObject:platform1];
[platforms addObject:platform2];
[platforms addObject:platform3];
[platforms addObject:platform4];
[platforms addObject:platform5];
}
- (void)gameLoop
{
playerVelocity = CGPointMake(playerVelocity.x,playerVelocity.y + gravity.y);
player.center = CGPointMake(player.center.x + playerVelocity.x,player.center.y + playerVelocity.y);
for(UIImageView *platform in platforms)
{
if(CGRectIntersectsRect(platform.frame,player.frame))
{
BOOL check = YES; //break point here to check if it reaches this point
}
}
}
另外,当我简单地输入:
if(CGRectIntersectsRect(platform1.frame,player.frame))
{
BOOL doubleCHECK = YES;
}
它起作用了。
发布于 2013-07-11 19:52:19
您未能分配平台数组。objective-c中的所有对象都是指针,因此,在您的viewDidLoad
方法中,您可能需要这样一行代码:
platforms = [[NSMutableArray alloc] init];
发布于 2013-07-11 19:52:33
如果你在循环之前检查platforms
,我相信你会发现它是nil
。您需要在使用它之前创建它(viewDidLoad
可能是最好的地方,除非您在加载视图之前需要它)-而且与某些语言不同的是,对空对象的操作将静默地返回0,而不是抛出异常。
https://stackoverflow.com/questions/17602139
复制