didBegin(联系人)只被调用一次

时间:2018-05-19 19:32:48

标签: swift sprite-kit skaction

我正在制作游戏,我正在多次调用一个函数,为场景添加一个节点。

我需要知道节点是否接触到了播放器。问题是只有当节点的第一个实例接触到播放器节点时才会调用didBegin(contact)方法,但是当被调用的其他实例触摸它时,它不会被调用。

以下是我正在使用的代码:

class GameScene: SKScene, SKPhysicsContactDelegate {

    let circlePlayer = SKSpriteNode(imageNamed: "Player")

    self.physicsWorld.contactDelegate = self
    circlePlayer.position = CGPoint(x: self.frame.midX, y:
    self.frame.minY + circlePlayer.size.height * 3)

    circlePlayer.zPosition = 2

    //Physics for player

    circlePlayer.physicsBody = SKPhysicsBody(circleOfRadius:
    circlePlayer.size.height / 2)
    circlePlayer.physicsBody?.categoryBitMask = PhysicsNumbering.player
    circlePlayer.physicsBody?.contactTestBitMask =
    PhysicsNumbering.star

    //Star node is called multiple times
    let star = SKAction.sequence([SKAction.run(starEmitter), SKAction.wait(forDuration: 3)])

 }

这是Star Node功能:

func starEmitter(){

    let star = SKSpriteNode(imageNamed: "15")

    //Physics World
    star.physicsBody = SKPhysicsBody(circleOfRadius: star.size.height / 2)
    star.physicsBody?.categoryBitMask = PhysicsNumbering.star
    star.physicsBody?.contactTestBitMask = PhysicsNumbering.player
    star.physicsBody?.affectedByGravity = false
    star.physicsBody?.isDynamic = true
    star.physicsBody?.collisionBitMask = 0

    star.zPosition = 0

    let tooMuch = self.frame.maxX

    let point1 = UInt32(tooMuch)


    star.position = CGPoint(x: CGFloat(arc4random_uniform(point1 * 2)) - CGFloat(point1)  ,y: self.frame.maxY )

    let move = SKAction.moveTo(y: self.frame.minY + 100, duration: 1.4)
    let removeNode = SKAction.removeFromParent()

    let sequence = SKAction.sequence([move,removeNode])

    star.run(sequence)
    addChild(star)
}

这是didBeginContact方法:

func didBegin(_ contact: SKPhysicsContact) {

    var BodyOne = SKPhysicsBody()
    var BodyTwo = SKPhysicsBody()


    if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask{
        BodyOne = contact.bodyA
        BodyTwo = contact.bodyB
    }
    else{
        BodyOne = contact.bodyB
        BodyTwo = contact.bodyA
    }

    //------------------------------------



    if BodyTwo.categoryBitMask == PhysicsNumbering.player && BodyOne.categoryBitMask == PhysicsNumbering.star{


        let scaleUp = SKAction.scale(by: 1.3, duration: 0.5)
        let fadeOut = SKAction.fadeOut(withDuration: 1)
        let removeNode = SKAction.removeFromParent()
        BodyOne.node?.removeAllActions()
        let group = SKAction.group([scaleUp,fadeOut])
        BodyOne.node?.run(SKAction.sequence([group,removeNode]))
        print("star touched")
    }


}

我试图在网上搜索,但找不到可能发生这种情况的原因。有人能告诉我我做错了什么吗?

提前谢谢你!

0 个答案:

没有答案