2

I have the following code:

in my scene:

static const uint32_t enermyCategory    =  0x1 << 0;
static const uint32_t fatherCategory    =  0x1 << 1;

self.physicsWorld.contactDelegate = self;

    //init ship
Ship *ship = [Ship getFather];
ship.position = CGPointMake(CGRectGetMaxX(self.frame) - ship.frame.size.width , ship.frame.size.height);
[self addChild: ship];

    //init enermy
    Enermy *ene = [[Enermy alloc] initWithImageNamed:enermyName gameScene:self];
ene.position = ship.position;
[self addChild:ene];

#pragma mark - Physics Delegate Methods
- (void)didBeginContact:(SKPhysicsContact *)contact{
    NSLog(@"contact detected");
}

As you can see, I set both ship and energy at the same location to start with, so they will always collide.

For both classes, I have the following code in their init method:

//setup physics body
self.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:self.size];
self.physicsBody.dynamic = NO;
self.physicsBody.categoryBitMask = enermyCategory; #shipCategory for ship
self.physicsBody.collisionBitMask = 0;
self.physicsBody.contactTestBitMask = shipCategory; #enermyCategory for ship

What I found is that the NSLog is never get called, so that the physical collision detection never works, I've read a lot from apple developer tutorials and it seems all the same of what they had, not sure why is not working. I can see the ship and energy images on screen collide each other.

4

2 回答 2

4
self.physicsBody.dynamic = NO;

静态(非动态)实体不会产生接触事件。让它们充满活力。

另外,我看到您正在将 gameScene 传递给 Enemy 的实例。如果 Enemy 对游戏场景(一个 ivar)有很强的引用,那么您可能会在这里创建一个保留循环(敌人保留场景,场景保留敌人)。

在 Sprite Kit 中,您可以简单地使用self.scene来访问场景,如果您在初始化期间需要场景,将该代码移动到设置方法中,并[ene setup]在将其添加为子项后立即调用以执行涉及场景的设置步骤。

于 2014-01-17T20:40:02.143 回答
4

将physicsBody 设置为dynamic = NO 不会影响接触。更有可能的情况是您为两个节点设置了相同的 contactBitMask 和 categoryBitMask。您应该将船设置为具有以下内容:

self.physicsBody.categoryBitMask = shipCategory;
self.physicsBody.collisionBitMask = 0;
self.physicsBody.contactTestBitMask = enermyCategory;

敌人应具备以下条件:

self.physicsBody.categoryBitMask = enermyCategory;
self.physicsBody.collisionBitMask = 0;
self.physicsBody.contactTestBitMask = shipCategory;

底线:它们应该在船上交换。

于 2014-01-20T05:50:48.220 回答