我目前正在爲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