Sprite Kit collision - 在碰撞的实例上执行实例方法

时间:2013-12-20 18:23:47

标签: objective-c collision-detection sprite-kit instance-methods

我在场景中添加了一个类的实例,并检测它们与另一个对象之间的碰撞。

所有设置和工作

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

每当我发生碰撞时获取“命中”日志。

我现在如何在其中一个对象上执行实例方法?

仅供参考,这是我添加其中一个对象。

    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];

2 个答案:

答案 0 :(得分:0)

我已经使用方法来执行此操作,我已将类别命名为您的名称,因此您应该能够复制并粘贴代码:),如果您有任何问题请告诉我。

- (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
} 

答案 1 :(得分:0)

这很简单:

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