在子类节点中没有检测到冲突

时间:2016-11-28 17:17:35

标签: swift sprite-kit

我正在写一个游戏。它没有检测到任何碰撞,即使我可以看到物理实体,因为我打开了那个视图。

为了在游戏场景中设置物理世界,我在类声明上面编写了以下代码:

struct PhysicsCategory {
    static let None: UInt32 = 0
    static let Chicken: UInt32 = 0b1
    static let Edge: UInt32 = 0b10
}

然后,在场景的实际类中:

override func didMove(to view: SKView) {
    setupNodes()
    setupTrial()

    let playableRect = CGRect(x: 0, y: 0, width: size.width/2, height: size.height/2)
    self.physicsBody = SKPhysicsBody(edgeLoopFrom: playableRect)
    self.physicsWorld.contactDelegate = self
    self.physicsBody!.categoryBitMask = PhysicsCategory.Edge
    self.physicsBody!.contactTestBitMask = PhysicsCategory.Chicken

    // This is important for handling all the custom events
    enumerateChildNodes(withName: "//*", using: { node, _ in
        // we need to limit this to chickens only
        if let customNode = node as? CustomNodeEvents {
            customNode.didMoveToScene()
        }
    })
}

以下是检测冲突的代码:

func didBegin(_ contact: SKPhysicsContact) {
    print("something happened")
    let collision = contact.bodyA.categoryBitMask |    contact.bodyB.categoryBitMask

    if collision == PhysicsCategory.Chicken | PhysicsCategory.Edge {
        print("it works!")
    }
}

我想要制作动画的节点是鸡。我希望游戏能够检测到它们与上面世界的边缘碰撞的时间。

我的鸡类是这样的:

class TargetNode: SKSpriteNode, CustomNodeEvents, InteractiveNode {

func didMoveToScene() {
    isUserInteractionEnabled = true

    anchorPoint = CGPoint(x: 0, y: 0)
    let playableRect = CGRect(x: self.anchorPoint.x, y: self.anchorPoint.y, width: self.size.width, height: self.size.height)

    physicsBody = SKPhysicsBody(edgeLoopFrom: playableRect)
    physicsBody!.isDynamic = true
    physicsBody!.categoryBitMask = PhysicsCategory.Chicken
    physicsBody!.contactTestBitMask = PhysicsCategory.Edge | PhysicsCategory.Chicken
    physicsBody!.velocity = CGVector(dx: 100, dy: 0)
}
}

编辑:在游戏场景文件中使用此方法将节点添加到场景中。

func generateItems(targetNumber: Int, target: Bool) {
    let movingItems = true
    for _ in 0...(targetNumber - 1) {
        if (target) {
            let name = createTarget()
            let targetNode = TargetNode(imageNamed: name)
            targetNode.name = name
            fgNode.addChild(targetNode)
            targetNode.position = generateRandomLocation()
            //if movingItems { animateTargets(targetNode) }
       }
}

1 个答案:

答案 0 :(得分:1)

将鸡肉设置为SKPhysicsBody(edgeLoopFrom :_)是一个坏主意。相反,尝试SKPhysicsBody(rectangleOf :_)在鸡的周围画一个矩形,你要绘制的形状类型可能会有所不同,请查看文档以获取更多信息。

此外,为了检查天气,鸡已与playableRect

联系

删除self.physicsBody!.contactTestBitMask = PhysicsCategory.Chicken,因为我们不想检查是否已经与我们想知道的鸡肉接触过鸡肉是否与可玩的Rect接触。所以保持鸡contactTestBitMask

从你的鸡类中删除| PhysicsCategory.Chicken,除非你想检查鸡的天气相互碰撞。

最后:如果鸡与playableRect接触,检查是否有碰撞

  func didBegin(_ contact: SKPhysicsContact) {

    if contact.bodyA.categoryBitMask == PhysicsCategory.Chicken && contact.bodyB.categoryBitMask == PhysicsCategory.Edge {
       print("Chickens have collided with edge")
    }

    }