简体   繁体   English

我的节点没有碰撞

[英]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(_:) . 您可以正确初始化球,但是可以通过在touchesBegan(_:)内部创建一个新球来删除它们的物理主体。 Just remove this line from the touchesBegan(_:) function: 只需从touchesBegan(_:)函数中删除此行:

 ball.physicsBody = SKPhysicsBody()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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