我目前正在为iOS创建一款非常基本的游戏。基本上,我在屏幕上设置了正方形动画,以及使用加速度计控制的“船”。我想检测船何时撞到正在移动的方格,并且由于某种原因我的代码无效。
在这个块中,我创建了一个正方形的动画:
square4 = [[UIImageView alloc] initWithFrame: CGRectMake(frameWidth/10, frameHeight/1.35, frameWidth*.1, frameWidth*.1)];
square4.image = [UIImage imageNamed: @"square.png"];
[self.view addSubview: square4];
CGPoint origin4 = square4.center;
CGPoint target4 = CGPointMake(square4.center.x+300, square3.center.y);
CABasicAnimation *bounce4 = [CABasicAnimation animationWithKeyPath:@"position.x"];
bounce4.fromValue = [NSNumber numberWithInt:origin4.x];
bounce4.toValue = [NSNumber numberWithInt:target4.x];
bounce4.duration = 2.3;
bounce4.repeatCount = HUGE_VALF;
bounce4.autoreverses = YES;
[square4.layer addAnimation:bounce4 forKey:@"position"];
然后我创造我的船,并设置加速度计等。我遇到的问题是,当我运行这种方法,船和方碰撞时,没有任何反应!这是我的碰撞方法代码:
- (void)collisionWithSquares {
CALayer *squareLayer1 = [square.layer presentationLayer];
CALayer *squareLayer2 = [square2.layer presentationLayer];
CALayer *squareLayer3 = [square3.layer presentationLayer];
CALayer *squareLayer4 = [square4.layer presentationLayer];
if (CGRectIntersectsRect(ship.frame, squareLayer1.frame)
|| CGRectIntersectsRect(ship.frame, squareLayer2.frame)
|| CGRectIntersectsRect(ship.frame, squareLayer3.frame)
|| CGRectIntersectsRect(ship.frame, squareLayer4.frame) ) {
//self.currentPoint = CGPointMake(0, 144);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Oops!"
message:@"Mission Failed!"
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
}
}
我在init方法中调用[self collisionWithSquares]:
self.motionManager = [[CMMotionManager alloc] init];
self.motionManager.accelerometerUpdateInterval = .05;
//accelerometer queues up the data
//handler calls outputaccelera
[self.motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:^(CMAccelerometerData *accelerometerData, NSError *error)
{
[self outputAccelerationData:accelerometerData.acceleration];
}];
[self.view addSubview: ship];
[self collisionWithSquares];
}
return self;
}
答案 0 :(得分:2)
if (CGRectIntersectsRect(imageView1.frame, imageView2.frame)) {
// Do whatever it is you need to do.
}
答案 1 :(得分:1)
使用“square.frame”,“square2.frame”等,而不是为碰撞检测创建CALayer。另外,只用一个条件测试你的if语句,看它是否会触发。