Reputation: 129
I am currently creating a very basic game for iOS. Basically, I have squares animating across the screen, and a "ship" that is controlled using the accelerometer. I want to detect when the ship hits the squares that are moving, and for some reason my code is not working.
In this block I am creating the animation of a square:
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"];
Then I create my ship, and set up the accelerometer, etc. The problem I am having is that when I run this method, and the ship and square collide, nothing happens! Here's my collision method code:
- (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];
}
}
I am calling [self collisionWithSquares] here in my init method:
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;
}
Upvotes: 0
Views: 1025
Reputation: 593
if (CGRectIntersectsRect(imageView1.frame, imageView2.frame)) {
// Do whatever it is you need to do.
}
Upvotes: 2
Reputation: 1474
use the "square.frame", "square2.frame", etc. rather then creating a CALayer for the collision detection. also, test your if statement with only one condition and see if it fires.
Upvotes: 1