SpriteKit碰撞检测不起作用

时间:2014-05-13 20:47:57

标签: ios7 collision-detection sprite-kit

我以为我理解了bitmasks,CategoryBitMasks和CollisionBitMasks的概念,但事实证明我不是;-( 但我不明白为什么。 我为碰撞检测设置了掩码,我将类别位掩码添加到帧中,然后将categoryBitMask添加到我的对象(在这种情况下是一个出租车)。但是出租车只是在屏幕上掉了下来: - /

为什么会这样?

#import "MyScene.h"
#import "SKSpriteNode+DebugDraw.h"

// Define Bit Masks for Collision Detection
typedef NS_OPTIONS(uint32_t, CNPhysicsCategory) {
    CNPhysicsCategoryEdge = 1 <<0,
    CNPhysicsCategoryTaxi = 1 <<1,

};

@interface MyScene() <SKPhysicsContactDelegate>
@end

@implementation MyScene{
    SKNode *_gameNode;
    SKSpriteNode *_taxiNode;
}

-(instancetype)initWithSize:(CGSize)size {
    if (self = [super initWithSize:size]) {
        [self initializeScene];
    }
    return self;
}

-(void)initializeScene{

    self.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:self.frame];
    self.physicsWorld.contactDelegate = self;
    self.physicsBody.categoryBitMask = CNPhysicsCategoryEdge;

    SKSpriteNode* bg = [SKSpriteNode spriteNodeWithImageNamed:@"background.png"];
    bg.position = CGPointMake(self.size.width/2, self.size.height/2);
    [self addChild: bg];

    [self addTaxi];

    _gameNode = [SKNode node];
    [self addChild:_gameNode];
}

-(void)addTaxi{
    _taxiNode = [SKSpriteNode spriteNodeWithImageNamed:@"taxi.png"];
    _taxiNode.position = CGPointMake(self.size.width/2, self.size.height/2);

    [self addChild:_taxiNode];

    CGSize contactSize = CGSizeMake(_taxiNode.size.width, _taxiNode.size.height);
    _taxiNode.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize: contactSize];
    [_taxiNode attachDebugRectWithSize:contactSize];

    _taxiNode.physicsBody.categoryBitMask = CNPhysicsCategoryTaxi;

}

1 个答案:

答案 0 :(得分:2)

我终于设法了 - 问题不在于碰撞检测,而是手机的布局,因为我没有使用viewWillLayoutSubviews方法替换ViewController中的viewDidLoad方法。 现在一切正常。

重要帖子如下:bodyWithEdgeLoopFromRect not working in landscape

感谢您的支持!