SpriteKit的didBeginContact无法调用

SpriteKit's didBeginContact can't be called

我测试了一个简单的场景。

无法调用函数didBeginContact

我已经尝试使用 collisionBitMasks1.physicsBody = SKPhysicsBody(circleOfRadius: 100)。问题一直存在。

我该如何解决?

import SpriteKit

class Test2Scene: SKScene, SKPhysicsContactDelegate {
    override func didMoveToView(view: SKView) {
        physicsWorld.contactDelegate = self
        physicsWorld.speed = 0


        let s1 = SKSpriteNode(imageNamed: kImagePlayer)
        s1.position = CGPointMake(100, 100)
        s1.physicsBody = SKPhysicsBody(rectangleOfSize: s1.size)
        s1.physicsBody?.categoryBitMask = 1
        s1.physicsBody?.contactTestBitMask = 2
        //s1.physicsBody?.collisionBitMask = 2
        self.addChild(s1)


        let s2 = SKSpriteNode(imageNamed: kImagePlayer)
        s2.position = CGPointMake(100, 500);
        s2.runAction(SKAction.moveToY(0, duration: 1))
        s2.physicsBody = SKPhysicsBody(rectangleOfSize: s2.size)
        s2.physicsBody?.categoryBitMask = 2
        //s2.physicsBody?.collisionBitMask = 1
        self.addChild(s2);

        print("view did load")
    }

    func didBeginContact(contact: SKPhysicsContact) {
        print("aaa")
    }
    func didEndContact(contact: SKPhysicsContact) {
        print("bbb")
    }
}

你的代码几乎全错了,但你的违规者是:

physicsWorld.speed = 0

来自文档:

The default value is 1.0, which means the simulation runs at normal speed. A value other than the default changes the rate at which time passes in the physics simulation. For example, a speed value of 2.0 indicates that time in the physics simulation passes twice as fast as the scene’s simulation time. A value of 0.0 pauses the physics simulation.

因此将其设置为 0.0 会暂停模拟。第二个问题是您的节点受重力影响,但您使用 SKAction 移动它们。这样你就把节点从物理模拟中拉出来,你可能会遇到奇怪的行为。

另外,我建议阅读 有关位掩码及其工作方式/应如何使用的内容。

找出原因。需要使用

s1.physicsBody!.dynamic = true
s2.physicsBody!.dynamic = true