简体   繁体   中英

Square collision detection problem (iPhone)

I know I've probably posted three questions related to this then deleted them, but thats only because I solved them before I got an answer. But, this one I can not solve and I don't believe it is that hard compared to the others. So, with out further ado, here is my problem:

So I am using Cocos2d and one of the major problem is they don't have buttons. To compensate for there lack in buttons I am trying to detect if when a touch ended did it collide with a square (the button). Here is my code:

- (void)ccTouchesEnded:(NSSet*)touches withEvent:(UIEvent*)event
{
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView:touch.view];
    NSLog(@"%f", 240-location.y);
    if (isReady == YES)
    {
        if (((240-location.y) <= (240-StartButton.position.x - 100) || -(240-location.y) >= (240-StartButton.position.x) + 100) && ((160-location.x) <= (160-StartButton.position.y) - 25 || (160-location.x) >= (160-StartButton.position.y) + 25))
        {
            NSLog(@"Coll:%f", 240-StartButton.position.x);
            CCScene *scene = [PlayScene node];
            [[CCDirector sharedDirector] replaceScene:[CCZoomFlipAngularTransition transitionWithDuration:2.0f scene:scene orientation:kOrientationRightOver]];
        }
    }
}

Do you know what I am doing wrong?

Why dont you just do

 if (isReady == YES)
{
    if (CGRectContainsPoint([StartButton boundingBox],location))
    {

        CCScene *scene = [PlayScene node];
        [[CCDirector sharedDirector] replaceScene:[CCZoomFlipAngularTransition transitionWithDuration:2.0f scene:scene orientation:kOrientationRightOver]];
    }
}

[StartButton boundingBox] returns the CGRect of the node and CGRectContainsPoint checks to see if the CGPoint location is inside of the button.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM