当碰撞发生时,self无法运行正确的方法

时间:2015-09-02 07:50:43

标签: objective-c sprite-kit nsmutablearray collision

我创建了一个NSMutableArray,它有3个节点,当英雄与它们碰撞时,自运行3种不同的方法(obj_1-> method_1,obj_2-> method_2 ....)我的问题是当英雄与obj_1碰撞时,自我有时运行方法_2,但有时它运行良好....似乎“自我”与这3种方法混淆。我不知道我的代码的哪一部分出了问题。

-(void)randomLetter{


obj_array = [[NSMutableArray alloc]initWithCapacity:3];

obj_1 = [SKSpriteNode spriteNodeWithImageNamed:@“1.png"];
obj_1.name = @“1”;

obj_2 = [SKSpriteNode spriteNodeWithImageNamed:@“2.png"];
obj_2.name = @“2”;

obj_3 = [SKSpriteNode spriteNodeWithImageNamed:@“3.png"];
obj_3.name = @“3”;



[obj_array addObject: obj_1];
[obj_array addObject: obj_2];
[obj_array addObject: obj_3];



NSUInteger random_obj = arc4random()%obj_array.count;

obj_x = [obj_array objectAtIndex:random_obj];
[obj_array removeObjectAtIndex:random_obj];


obj_x.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius: obj_x.size.width/2];
obj_x.physicsBody.dynamic = NO;
obj_x.physicsBody.categoryBitMask = objCategory;
obj_x.physicsBody.contactTestBitMask = heroCategory;

obj_x.position = CGPointMake(self.size.width*1.1, self.size.height*0.5);
SKAction *obj_action= [SKAction moveToX:-self.size.width*1.1 duration:5];


[obj_x runAction:obj_action];
[self addChild: obj_x];
}


-(void)didBeginContact:(SKPhysicsContact *)contact{

SKPhysicsBody *firstBody, *secondBody;
if (contact.bodyA.categoryBitMask<contact.bodyB.categoryBitMask) {
    firstBody = contact.bodyA;
    secondBody = contact.bodyB;
}
else
{
    firstBody=contact.bodyB;
    secondBody=contact.bodyA;
}


    if ((firstBody.categoryBitMask & heroCategory ) !=0 && (secondBody.categoryBitMask & objCategory)!=0) {

        [self enumerateChildNodesWithName:@“1” usingBlock:^(SKNode *node, BOOL *stop) {

            _timeIsUp = NO;

            [obj_x removeFromParent];

           [self method_1];


        }];


        [self enumerateChildNodesWithName:@“2” usingBlock:^(SKNode *node, BOOL *stop) {

            _timeIsUp = NO;

            [obj_x removeFromParent];

            [self method_2];

        }];


        [self enumerateChildNodesWithName:@“3” usingBlock:^(SKNode *node, BOOL *stop) {

            _timeIsUp = YES;

            [obj_x removeFromParent];

            [self method_3];                
        }];

      }
}

1 个答案:

答案 0 :(得分:0)

如果您打算在英雄与method_n(n = 1,2,3)发生碰撞时致电obj_n,我认为以下方法更为明确。试试看你是否有任何问题。

if ((firstBody.categoryBitMask & heroCategory) !=0 && (secondBody.categoryBitMask & objCategory)!=0) {
    if ([secondBody.node.name isEqual:@"1"]) {
        _timeIsUp = NO;
        [secondBody.node removeFromParent];
        [self method_1];
    } else if ([secondBody.node.name isEqual:@"2"]) {
        _timeIsUp = NO;
        [secondBody.node removeFromParent];
        [self method_2];
    } else if ([secondBody.node.name isEqual:@"3"]) {
        _timeIsUp = NO;
        [secondBody.node removeFromParent];
        [self method_3];
    }   
}