Cocos2d - 移动前检查地点是否空闲(所有对象)

时间:2012-02-09 00:42:19

标签: objective-c ios cocos2d-iphone

在Cocos2d中是否有类似CGRectIntersectsRect的方法,除了将其限制为一个精灵,它会检查所有对象?

2 个答案:

答案 0 :(得分:0)

你可以设置这样的方法

CGRect sprite1Rect = CGRectMake(
                               sprite1.position.x - (sprite1.contentSize.width/2), 
                               sprite1.position.y - (sprite1.contentSize.height/2), 
                               sprite1.contentSize.width, 
                               sprite1.contentSize.height);
CGRect somethingRect = CGRectMake(
                             something.position.x - (something.contentSize.width/2), 
                             something.position.y - (something.contentSize.height/2), 
                             something.contentSize.width, 
                             something.contentSize.height);
CGRect something2Rect = CGRectMake(
                             something2.position.x - (something2.contentSize.width/2), 
                             something2.position.y - (something2.contentSize.height/2), 
                             something2.contentSize.width, 
                             something2.contentSize.height);

if (CGRectIntersectsRect(sprite1Rect, somethingRect) || CGRectIntersectsRect(sprite1Rect, something2Rect)) {
    // do something
}

if (CGRectIntersectsRect(sprite1.frame, something.frame) || CGRectIntersectsRect(sprite1Rect, something2Rect)) {
    // do something
}

这意味着如果sprite1与某些东西相交,那么它会做某事

答案 1 :(得分:0)

你可以循环完成。这个例子是一个精灵实例(即玩家)测试其他精灵数组的方法。

- (BOOL) checkForCollision
{
    BOOL didCollide = NO;
    CGRect myRect;
    CGRect testRect;

    // assuming anchor point is in the center
    myRect = CGRectMake(self.position.x - self.contentSize.width /2,
                        self.position.y - self.contentSize.height /2,
                        self.contentSize.width,
                        self.contentSize.height);


    for (CCSprite * currSprite in listOfWallSprites) {
        testRect = CGRectMake(currSprite.position.x - currSprite.contentSize.width /2,
                              currSprite.position.y - currSprite.contentSize.height /2,
                              currSprite.contentSize.width,
                              currSprite.contentSize.height);

        if ( CGRectIntersectsRect(myRect, testRect) ) {
            didCollide = YES;
            return didCollide;
        }

    }
    return didCollide;
}