为什么Sprite Kit会在这里引起碰撞?

时间:2014-06-12 23:48:37

标签: ios sprite-kit

我有一个文件Categories.h,它定义了我的SpriteKit游戏的类别位掩码。里面是这个:

#ifndef BallRoll_Categories_h
#define BallRoll_Categories_h

static u_int8_t ballCategory = 2;
static u_int8_t collideCategory = 6;
static u_int8_t contactCategory = 4;

#endif

我还有一个名为BRPowerup的类,其实现中包含此方法:

-(id)initWithType:(int)type
{
    if(self = [super init])
    {
        self.powerupType = type;
        self.size = CGSizeMake(32, 32);
        self.texture = [SKTexture textureWithImageNamed:sprites[self.powerupType]];
        self.name = @"powerup";
        self.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:self.size.width / 2];
        self.physicsBody.dynamic = NO;
        self.physicsBody.affectedByGravity = NO;
        self.physicsBody.categoryBitMask = contactCategory;
        self.physicsBody.collisionBitMask = 0;
        self.physicsBody.contactTestBitMask = ballCategory;
        NSLog(@"init");
    }
    return self;
}

BRMyScene.h内,此代码在initWithSize:方法中运行。

self.ball = [SKSpriteNode spriteNodeWithImageNamed:@"ball.png"];
        self.ball.position = CGPointMake(100, 100);
        self.ball.size = CGSizeMake(32, 32);
        self.ball.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:self.ball.size.width / 2];
        self.ball.physicsBody.density = .7;
        self.ball.physicsBody.restitution = .25;
        self.ball.physicsBody.categoryBitMask = ballCategory;
self.ball.physicsBody.contactTestBitMask = contactCategory;
        self.ball.physicsBody.collisionBitMask = collideCategory;
        self.ball.name = @"ball";
        [self addChild:self.ball];

完全可以检测到联系人,但是球仍会与collideCategory之外的事物发生碰撞并从通电中弹回。它还会与collideCategory之外的其他东西发生碰撞。

如果需要更多代码,请发表评论。

帮助将不胜感激!提前感谢您的回答。

1 个答案:

答案 0 :(得分:1)

您已按以下方式声明了类别掩码 -

static u_int8_t ballCategory = 2;    // 00000010
static u_int8_t collideCategory = 6; // 00000110
static u_int8_t contactCategory = 4; // 00000100

collideCategory 似乎等于 ballCategory | contactCategory

线self.ball.physicsBody.collisionBitMask = collideCategory;用于将球设置为与 ballCategory contactCategory 的其他物理主体发生碰撞。

collideCategory 设为自己的类别,为其提供类似00001000的唯一位,等于8.尝试collideCategory = 8而不是6。

最后一点需要注意的是,根据您的声明,我认为位掩码应该是32位( uint32_t )掩码而不是8位( u_int8_t )。试试这个 -

static const uint32_t ballCategory = 0x1 << 1;    // 00000010 (last 8 bits of 32bit mask)
static const uint32_t contactCategory = 0x1 << 2; // 00000100
static const uint32_t collideCategory = 0x1 << 3; // 00001000