0

我目前正在为 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;
}
4

2 回答 2

2
if (CGRectIntersectsRect(imageView1.frame, imageView2.frame)) {
// Do whatever it is you need to do.
}
于 2013-10-07T20:43:41.640 回答
1

使用“square.frame”、“square2.frame”等,而不是为碰撞检测创建 CALayer。另外,只用一个条件测试你的 if 语句,看看它是否会触发。

于 2013-10-07T20:28:36.280 回答