【问题标题】:Is there a way to detect collisions between 2 SKSpriteNodes but allow them to overlap有没有办法检测 2 个 SKSpriteNodes 之间的冲突但允许它们重叠
【发布时间】:2013-12-08 00:28:27
【问题描述】:

我认为没有办法做到这一点,但是有没有办法检测 2 个 SKSpriteNode 何时相互交叉,但仍然允许它们重叠,所以它们实际上不会相互反弹?

我知道我可以只拥有 1 没有物理实体,然后编写一些代码来检查它们的坐标,但我想我可能会在 Sprite Kit 中遗漏一些东西,我可以用 SK 方法检测到这一点。

【问题讨论】:

    标签: ios objective-c sprite-kit skspritenode


    【解决方案1】:

    您可以使用SKPhysicsWorld 对象的contactDelegate 属性:

    // inside your header file
    
    typedef NS_OPTIONS(NSUInteger, CollisionCategory) {
        categoryOne = (1 << 0),
        categoryTwo = (1 << 1)
    };
    
    // inside your SKScene sub-class implementation
    
    - (void)setupContactDelegate {
        self.physicsWorld.contactDelegate = self;
    
        nodeA.categoryBitMask = categoryOne;    // nodeA is category one
        nodeA.collisionBitMask = ~categoryTwo;  // nodeA does not collide w/ category two
        nodeA.contactTestBitMask = categoryTwo; // nodeA tests for contacts w/ category two
    
        nodeB.categoryBitMask = categoryTwo;    // nodeB is category two
        nodeB.collisionBitMask = ~categoryOne;  // nodeB does not collide w/ category one
        nodeB.contactTestBitMask = categoryOne; // nodeB tests for contacts w/ category one
    }
    
    - (void)didBeginContact:(SKPhysicsContact *)contact {
        // do whatever you need to do when the contact begins
    }
    
    - (void)didEndContact:(SKPhysicsContact *)contact {
        // do whatever you need to do when the contact ends
    }
    

    您还需要将您的SKScene 子类声明为实现SKPhysicsContactDelegate 协议。

    这里有更多参考信息:

    【讨论】:

    • 是的,这很好,但我试图检测一个有物理体的物体和一个没有物理体的物体之间的接触,我认为这是不允许的,你不必连接contactTestBitMask 到物理体?
    • 是的,你需要一个物理体,但是你可以将body的dynamic设置为NO,将collisionBitMask设置为0x00000000,它不会与任何东西交互。跨度>
    • 你不知道我花了多长时间寻找这样一个明确的答案!谢谢!
    • 哇,我完全不知道那个~类别的东西。谢谢老兄。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-15
    • 2018-02-17
    • 2013-07-27
    • 2016-07-02
    • 2017-04-02
    • 1970-01-01
    • 2021-12-21
    相关资源
    最近更新 更多