如何阻止力量应用于SKSprtieNode?

时间:2016-03-25 03:34:18

标签: xcode swift sprite-kit sknode

我有几个小桨彼此相邻排列,大小约为50x10,从左到右,从右到左不断移动,也会不时地随机停止移动并变得静止。有一个球朝向它们落下,并且在击中桨时,如果它没有移动并且是静止的,则球将从它上弹起并直接向上移动。然而,如果桨在移动并且球在那段时间内撞击其中一个桨,而不是球击中它们并向右上升,它击中桨并开始向右或向左移动(取决于桨的方向)回去的时候。我试图让球直接向后移动,即使它在移动时击中桨(几乎是一个永远弹跳球对着桨)。

我已经尝试了几种不同的方法来解决这个问题,但我认为我错过了一些重要的东西,让它表现得像这样。这是代码:

class GameScene: SKScene, SKPhysicsContactDelegate {
        let greenPaddle = SKSpriteNode(imageNamed: "Green")
        var ball = SKSpriteNode()

        let ballCategory: UInt32 = 1 << 0
        let greenPaddleCategory: UInt32 = 1 << 1

        override func didMoveToView(view: SKView) {

            self.physicsWorld.contactDelegate = self

            greenPaddle.position = CGPoint(x: 0, y: frame.size.height / -6.5)
            greenPaddle.physicsBody = SKPhysicsBody(rectangleOfSize: greenPaddle.size)
            greenPaddle.physicsBody!.affectedByGravity = false
            greenPaddle.physicsBody!.dynamic = false

            greenPaddle.physicsBody!.categoryBitMask = greenPaddleCategory
            greenPaddle.physicsBody!.contactTestBitMask = ballCategory


          ball = SKSpriteNode(imageNamed: "Red")
          ball.position = CGPoint(x: self.frame.size.width / 2, y: self.frame.size.height / 2)
          ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.height / 2)
          ball.physicsBody!.friction = 0
          ball.physicsBody!.restitution = 1
          ball.physicsBody!.linearDamping = 0
          ball.physicsBody!.allowsRotation = false

         ball.physicsBody!.categoryBitMask = ballCategory
         ball.physicsBody!.contactTestBitMask = greenPaddleCategory

         addChild(circle)
    }

    func didBeginContact(contact: SKPhysicsContact) {

        let bodyA = (contact.bodyA.categoryBitMask <= contact.bodyB.categoryBitMask) ? contact.bodyA : contact.bodyB
        let bodyB = (contact.bodyA.categoryBitMask <= contact.bodyB.categoryBitMask) ? contact.bodyB : contact.bodyA

        if (bodyA.categoryBitMask) == ballCategory && (bodyB.categoryBitMask) == greenPaddleCategory {

            greenPaddle.physicsBody!.friction = 0
            greenPaddle.physicsBody!.restitution = 0  
    }

}

1 个答案:

答案 0 :(得分:0)

我真的不明白这个问题;但是,你忘了在didmovetoview中设置物理世界。

 self.physicsWorld.contactDelegate = self

如果问题是联系人不起作用,这将起作用:)