我的节点没有碰撞

时间:2017-09-01 15:10:25

标签: ios swift sprite-kit

class GameScene: SKScene, SKPhysicsContactDelegate {

let balls = [
    SKSpriteNode(imageNamed: "blueball.png"),
    SKSpriteNode(imageNamed: "greenball.png"),
    SKSpriteNode(imageNamed: "realredball.png")
]


let redRectangle = SKSpriteNode(imageNamed: "redrectangle.png")
let blueRectangle = SKSpriteNode(imageNamed: "bluerectangle.png")
let greenRectangle = SKSpriteNode(imageNamed: "greenrectangle.png")

override func didMove(to view: SKView) {
    spawnBalls()
    rectangles()
    physicsWorld.contactDelegate = self

}
override func touchesBegan(_ touches: Set<UITouch>, with event:      UIEvent?) {
        for ball in balls{
            ball.physicsBody = SKPhysicsBody()
            ball.physicsBody?.affectedByGravity = true
            }
   }

func spawnBalls() {

    let ball = balls[Int(arc4random_uniform(UInt32(balls.count)))]
    ball.physicsBody = SKPhysicsBody()
    ball.physicsBody?.affectedByGravity = false
    ball.position = CGPoint(x: 0, y: 250)
    ball.size = CGSize(width: 70, height: 70)
    ball.physicsBody?.categoryBitMask = 0
    ball.physicsBody?.collisionBitMask = 1
    self.addChild(ball)
}

func rectangles() {
    redRectangle.position = CGPoint(x: -316.5, y: -657)
    redRectangle.size = CGSize(width: 400, height: 20)
    redRectangle.physicsBody = SKPhysicsBody()
    redRectangle.physicsBody?.categoryBitMask = 1
    redRectangle.physicsBody?.collisionBitMask = 0
    blueRectangle.size = CGSize(width: 400, height: 20)
    blueRectangle.position = CGPoint(x: -100, y: -657)
    blueRectangle.physicsBody = SKPhysicsBody()
    greenRectangle.position = CGPoint(x: 0, y: -657)
    greenRectangle.size = CGSize(width: 400, height: 20)
    greenRectangle.physicsBody = SKPhysicsBody()
    self.addChild(redRectangle)
    self.addChild(blueRectangle)
    self.addChild(greenRectangle)
}

}

我希望球能够下降并与矩形节点接触,尽管它看起来像球正在通过它们。我使用了碰撞和类别位掩码。我想知道是否有人可以帮助解决这个问题,谢谢。

1 个答案:

答案 0 :(得分:0)

你正确地初始化球,但是通过在touchesBegan(_:)内创建一个新的物体来移除它们。只需从touchesBegan(_:)函数中删除此行:

 ball.physicsBody = SKPhysicsBody()