Action in collision detection (CGRectIntersectsRect)

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-08 14:06:57

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!