我目前正在为iOS创建一个非常基本的游戏。基本上,我有在屏幕上动画的正方形,以及使用加速度计控制的“船”。我想要检测船舶何时撞到正在移动的方格,出于某种原因,我的代码无法工作。检测两幅图像是否在objective-C和打印信息中相撞
在该块中我创建一个正方形的动画:
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];
}
}
我打电话[自collisionWithSquares]在这里我的init方法:
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;
}
hmm。我尝试了所有这些,但仍然没有运气。我也尝试在显示器上制作船只图像,并将其作为静态图像进行测试,以查看它是否仅仅是我的加速度计代码中的错误,但没有任何运气。 – Copernikush
如果你只在你的init方法中调用[self collisionWithSquares],那么这就是你的问题。那只会被调用一次。你需要某种“运行循环”来持续检查碰撞是否发生。您可能需要设置NSTimer以持续激活该方法,或者在加速度计更改时调用该方法。 – DoS
我也可以在我的outputAccelerationData方法中调用它吗?这样它不会被调用一次。我试图在那里调用它,但仍然没有。 – Copernikush