简体   繁体   中英

My nodes aren't colliding

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)
}

}

I want the balls to drop down and make contact with the rectangle nodes, although it looks like the balls are just going through them. I used collision and category bitmask. I'm wondering if someone could help fix this problem, thanks.

You initialise the balls correctly, but remove their physics body by creating a new one inside touchesBegan(_:) . Just remove this line from the touchesBegan(_:) function:

 ball.physicsBody = SKPhysicsBody()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM