0

您好,我正在制作 cocos2d 侧滚动条。我正在尝试测试两个精灵之间的碰撞。我检查了一下,我为精灵制作的矩形是它们应该是的,但它说这两个矩形总是相交,无论它们是否真的相交。这是代码:

-(void)checkForRedEnemyCollisions{
    CGRect playerRect = CGRectMake(player.position.x -     (player.playerSprite.contentSize.width/2),
                                   player.position.y -     (player.playerSprite.contentSize.height/2),
                                   player.playerSprite.contentSize.width,
                                   player.playerSprite.contentSize.height);

    CGRect redEnemyRect = CGRectMake(redEnemy.position.x -     (redEnemy.bulletSprite.contentSize.width / 2) ,
                                     redEnemy.position.y -     (redEnemy.bulletSprite.contentSize.height /2 ),
                                     redEnemy.bulletSprite.contentSize.width,
                                     redEnemy.bulletSprite.contentSize.height);
    if (CGRectIntersectsRect(playerRect, redEnemyRect)) {
        CCLOG(@"collision");
    }
}

这是更多代码:

-(id)init{
if((self = [super init])){
    CGSize size = [[CCDirector sharedDirector]winSize];
    screenWidth = size.width;
    screenHeight = size.height;

    gravity = 2;

    playerSprite = [CCSprite spriteWithFile:@"thefinalcharacter.png"];
    playerSprite.scale = 1.5;
    playerSprite.position = ccp(screenWidth/3.4, screenHeight/2);
    [self addChild:playerSprite z:-3];

    [self schedule: @selector(flight:)interval:1.0f/7.0f];

    }
return self;
}

-(void)flight:(ccTime)delta{
flightCounter ++;

if (flightCounter % 2){
    [playerSprite setTexture:[[CCSprite spriteWithFile:@"thefinalcharacter.png"]texture]];
}else{
    [playerSprite setTexture:[[CCSprite    spriteWithFile:@"thefinalcharacter2.png"]texture]];
}
[self schedule:@selector(updatePosition:)interval:1.0f/30.0f];
}

-(void)updatePosition:(ccTime)delta{
if(playerSprite.position.y < 35){
    gravity = 0;
}else if(playerSprite.position.y > screenHeight - 150) {
        playerSprite.position = ccp(playerSprite.position.x, playerSprite.position.y -    100);
}else{
    gravity = 2;
}

playerSprite.position = ccp(playerSprite.position.x, playerSprite.position.y - gravity);
}
4

1 回答 1

0

确保您在世界坐标中创建边界矩形。

尝试将点转换为世界坐标,如下所示;

CGPoint playerWorldPosition = [player ConvertToWorldSpace:player.position];
CGRect playerRect = CGRectMake(playerWorldPosition.x -  (player.playerSprite.contentSize.width/2),
                               playerWorldPosition.y -  (player.playerSprite.contentSize.height/2),
                               player.playerSprite.contentSize.width,
                               player.playerSprite.contentSize.height);

对 redEnemy 做同样的事情。这将确保您在世界空间中比较它们,而不是在层层次结构中的另一个空间中进行比较。

如果您在播放器或 redEnemies 上使用锚点而不是默认的 (0.0,0.0)。使用 ConvertToWorldSpaceAR 函数而不是 ConvertToWorldSpace。

于 2013-09-02T15:55:51.523 回答