我目前使用两个类: Player和Ball ( Monster类的儿子)。有了d-pad,我就可以在屏幕上移动球员,球就会在屏幕上不断弹跳。在ViewController中,我有一个球员的NSMutableArray和一个NSMutableArray的球。
Player *m = [[Car alloc]init];
[players addObject:m];
[self.view addSubview:m.image];
joypad = [[Joypad alloc] initWithPlayer:players[0]];
[self.view addSubview: joypad.pad];
[self.view addSubview:joypad.movingPad];
monsters = [NSMutableArray arrayWithCapacity:MAX];
for(int i = 0; i < MAX; ++i)
{
int radius = rand()%100;
int deltax = rand()%5 + 1;
int deltay = rand()%5 +1;
Monster *ball = [[Ball alloc] initWithRadius:radius andDX:deltax DY:deltay];
[self.view addSubview:ball.image];
[ball startMoving];
}如何检测球与球之间的碰撞以及球与球员之间的碰撞?enter link description here
我尝试在VievController的viewDidLoad中调用此方法(checkCllisions),但它没有显示任何消息:
-(void) checkCollisions{
[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(collisions) userInfo:nil repeats:YES];
}
-(void) collisions{
for(int i = 0; i < [players count]; i++){
Player *p = players[i];
CGRect f = CGRectMake(p.image.frame.origin.x, p.image.frame.origin.y, p.image.frame.size.width, p.image.frame.size.height);
for (int k = 0; k < [monsters count]; i++){
Monster *m = monsters[i];
CGRect fm = CGRectMake(m.image.frame.origin.x, m.image.frame.origin.y, m.image.frame.size.width, m.image.frame.size.height);
if(CGRectIntersectsRect(f, fm))
NSLog(@"collision");
}
}
}发布于 2013-05-25 03:02:36
在collision方法的内部循环中有两个错误:应该递增k而不是i,并且monsters[i]应该是monsters[k]。
请注意,可以简化CGRects的分配:
-(void) collisions{
for(int i = 0; i < [players count]; i++){
Player *p = players[i];
CGRect f = p.image.frame;
for (int k = 0; k < [monsters count]; k++){
Monster *m = monsters[k];
CGRect fm = m.image.frame;
if(CGRectIntersectsRect(f, fm))
NSLog(@"collision");
}
}
}https://stackoverflow.com/questions/16741831
复制相似问题