سؤال

Im adding a load of instances of a class to my scene and detecting a collision between them and another object.

All set up and working

if ((firstBody.categoryBitMask & ballCategory) != 0 && (secondBody.categoryBitMask & objectCategory) != 0) {
    NSLog(@"Hit");
}

Getting the "Hit" log whenever I get a collision.

How do I now perform an instance method on one of those objects?

Just for reference this is me adding one of the objects.

    Ball *ball = [[Ball alloc]init];
    ball.position = CGPointMake(spawnPoint.x + arc4random() % 5, spawnPoint.y);
    ball.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:5];
    ball.physicsBody.dynamic = YES;
    ball.physicsBody.mass = 10;
    ball.name = @"ball";
    ball.physicsBody.categoryBitMask = ballCategory;
    ball.physicsBody.contactTestBitMask = targetCategory | ballCategory;
    ball.physicsBody.collisionBitMask = targetCategory | ballCategory | objectCategory;
    [self addChild:ball];
هل كانت مفيدة؟

المحلول

It's very simple:

if ((firstBody.categoryBitMask & ballCategory) != 0 && 
     (secondBody.categoryBitMask & objectCategory) != 0) {
     NSLog(@"Hit");
     Ball *ball = (Ball*)firstBody.node;
     [ball someMethod];
}

نصائح أخرى

I have put in the method to do this, I have named the category's to your names so you should just be able to copy and paste the code :), if you have any troubles let me know.

- (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 & ballCategory) != 0 &&
    (secondBody.categoryBitMask & objectCategory) != 0)
{
//stuff that u want to call when collision happens
} 
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top