问题
I have two images. You have to use a acceleremoter
to move a man and avoid a big spike. Here is my .h coding:
IBOutlet UIImageView *rect1;
IBOutlet UIImageView *rect2;
Here is my .m:
bool CGRectIntersectsRect ( CGRect rect1, CGRect rect2 );
I have connected everything in the nib file and I know nothing would happen because there was no error. I need these two things to collide and then generate an end screen. BUT HOW do I put an action in. THANKS!
.m
#import "GameScreen.h"
@implementation GameScreen
@synthesize ball, delta;
-(void)viewDidLoad {
UIAccelerometer *accel = [UIAccelerometer sharedAccelerometer];
accel.delegate = self;
accel.updateInterval = 1.0f / 60.0f;
[super viewDidLoad];
}
-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
NSLog(@"x : %g", acceleration.x);
NSLog(@"y : %g", acceleration.y);
NSLog(@"z : %g", acceleration.z);
delta.y = acceleration.y * 70;
delta.x = acceleration.x * 70;
ball.center = CGPointMake(ball.center.x + delta.x, ball.center.y + delta.y);
// Right
if(ball.center.x < 0) {
ball.center = CGPointMake(320, ball.center.y);
}
// Left
if(ball.center.x > 320) {
ball.center = CGPointMake(0, ball.center.y);
}
// Top
if(ball.center.y < 0) {
ball.center = CGPointMake(ball.center.x, 460);
}
// Bottom
if(ball.center.y > 460){
ball.center = CGPointMake(ball.center.x, 0);
}
}
bool CGRectIntersectsRect ( CGRect rect1, CGRect rect2 );
-(void)dealloc {
[super dealloc];
}
@end
回答1:
Just before the end of
-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
you have to put this code
if(CGRectIntersectsRect(ball.bounds , man.bounds))
{
UIImage *image = [UIImage imageNamed:@"endScreenImage.png"];
UIImageView *imageview = [[UIImageView alloc] initWithImage:image];
[self.view addSubView:imageview];
[imageview release];
}
But I also think that you have to buy an Objective-C programming book and read it, instead of spamming StackOverflow with a lot of similar questions. I wrote that because I think it can be useful to you, not to make you angry.
回答2:
You can try this, just donne if its gonna work with ImageView's
init
[self schedule:@selector(update:)];
Make a void
- (void)update:(ccTime)dt {
...
CGRect absoluteBox = CGRectMake(ball.position.x, ball.position.y, [ball boundingBox].size.width, [ball boundingBox].size.height);
if (CGRectIntersectsRect([ball boundingBox], [man boundingBox])) {
// SOME CODE HERE
}
...
}
来源:https://stackoverflow.com/questions/5845692/action-in-collision-detection-cgrectintersectsrect