【问题标题】:Cocos2d Sprite collision detection during action动作时的Cocos2d Sprite碰撞检测
【发布时间】:2013-12-10 14:06:25
【问题描述】:

我无法检测到两个精灵之间的碰撞,其中一个正在移动。

我有一个“Enemy”类精灵,通过 CCMoveTo 在屏幕上移动,另一个“Hero”类精灵,由触摸控制,都添加到“MainGame”类的场景中

以下说明如何将两个精灵添加到场景中以及如何操作敌人:

MainGame.m

-(id) init{
if( (self=[super init]) ) {
    _enemies = [[NSMutableArray alloc]init];

    _enemyLink = [Enemy nodeWithTheGame:self];
    _enemyLink.position = ccp(10, 10);
    [self.enemies addObject:_enemyLink];
    CCMoveTo *test = [CCMoveTo actionWithDuration:40 position:ccp(500, 250)];
    [_enemyLink runAction:test];

    _heroArray = [[NSMutableArray alloc]init];
    _heroLink = [Hero nodeWithTheGame:self location:ccp(100,100)];
    [_heroArray addObject:_heroLink];

    [self scheduleUpdate];
    }
}



-(void)update:(ccTime)delta{

    if (CGRectIntersectsRect([self.enemyLink.enemySprite boundingBox], [self.heroLink.heroSprite boundingBox])) {
        NSLog(@"rect intersects rect");  
    }

    for (CCSprite *enemies in self.enemies) {
        NSLog(@"enemy position: %f, %f",enemies.position.x,enemies.position.y);
    }
}

我无法在动作期间和之后检测到这两个精灵之间的碰撞。但是,如果我将英雄移动到场景中的位置 (0,0),我的代码中的日志将触发,并且两者将进行攻击。

更新中的 for 循环表明 Enemy 精灵位置在动作期间不断移动。因此,为什么我不知道为什么没有检测到碰撞。

【问题讨论】:

    标签: ios cocos2d-iphone


    【解决方案1】:

    您是否检查过敌人和英雄的位置是否在同一个坐标空间内进行了测试?

    这是因为 boundingBox() 是本地的,相对于其父节点,如果您比较的节点没有相同的父节点,则检查将无效。

    您可以在检查边界框之前使用 convertToNodeSpace()/convertToWorldSpace()。

    此处可能与您的案例相关的另一个答案:A sprite bounding box shows wrong position after moving the layer

    【讨论】:

    • 你是对的Loic,使用类似的for循环检查英雄类实例的x,y坐标表明它没有在世界空间更新,并且一直在0,0甚至如果精灵被移动。你知道我如何改变英雄精灵的坐标系吗?我曾尝试调用 [hero.parent convertToWorldSpace:hero.position];没有太大的成功。
    • 基本上,为第一个精灵计算一个矩形,然后使用它们的位置为第二个精灵计算一个矩形。像这样:stackoverflow.com/questions/5822077/…。对于每个精灵,使用投射到相同坐标系中的校正位置(这取决于您自己的节点层次结构),如下所示:stackoverflow.com/questions/16268213/…。希望这会有所帮助。
    • 另外,请注意,如果您开始旋转精灵并应用其他变换,它会变得更加复杂。在这种情况下,您需要在计算中考虑到这一点。但如果你到了那里,你可能想考虑一下 Chipmunk 或 Box2d。
    猜你喜欢
    • 1970-01-01
    • 2011-08-14
    • 2014-01-09
    • 1970-01-01
    • 1970-01-01
    • 2014-05-05
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    相关资源
    最近更新 更多