swift:未检测到sprite kit冲突和位掩码

时间:2014-11-22 16:11:33

标签: ios swift sprite-kit game-physics skphysicsbody

我遇到以下精灵套件代码的问题。我试图检测一个飞球何时与一条线发生碰撞。但是当两者发生碰撞时没有任何反应。但是当球击中场景边缘时,会打印出以下内容:

联系1 bitmask1:4294967295 bitmask2:4294967295

问题1:为什么没有检测到线和球的碰撞? 问题2:为什么边缘碰撞时两个位掩码都相同?如果我不知道哪个是哪个,我就无法与身体一起工作。

struct PhysicsCategory {
    static let None      : UInt32 = 0
    static let All       : UInt32 = UInt32.max
    static let Ball      : UInt32 = 0b1       // 1
    static let Line      : UInt32 = 0b10      // 2
    static let Shape     : UInt32 = 0b100     // 3 or 4?
}
override func didMoveToView(view: SKView) {
    /* Setup your scene here */       
    physicsWorld.contactDelegate = self

    self.physicsBody = SKPhysicsBody(edgeLoopFromRect: view.frame);
    self.physicsWorld.gravity = CGVectorMake(0.0, 0.0);

    let ball = SKShapeNode(circleOfRadius: 5)
    ball.fillColor = UIColor.whiteColor()
    ball.strokeColor = UIColor.whiteColor()
    ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.frame.size.width/2)
    ball.physicsBody?.velocity = CGVector(dx: 200.0, dy: 200.0)
    ball.position = CGPoint(x: view.bounds.width/2, y:view.bounds.height/2)
    ball.physicsBody?.friction = 0.0;
    ball.physicsBody?.restitution = 1.0;
    ball.physicsBody?.linearDamping = 0.0;
    ball.physicsBody?.allowsRotation = false
    ball.physicsBody?.applyImpulse(CGVector(dx:CGFloat(100), dy:CGFloat(100)));
    ball.physicsBody?.categoryBitMask = PhysicsCategory.Ball
    ball.physicsBody?.dynamic = true
    ball.physicsBody?.contactTestBitMask = PhysicsCategory.Line
    ball.physicsBody?.collisionBitMask = PhysicsCategory.Line
    self.addChild(ball)
}

覆盖func touchesMoved(触及:NSSet,withEvent事件:UIEvent){         / *触摸开始时调用* /

    touch = touches.anyObject() as UITouch!

    var linePhysicsBody = SKPhysicsBody()
    linePhysicsBody.categoryBitMask = PhysicsCategory.Line
    linePhysicsBody.contactTestBitMask = PhysicsCategory.Ball
    linePhysicsBody.collisionBitMask = PhysicsCategory.Ball
    linePhysicsBody.dynamic = false
    linePhysicsBody.usesPreciseCollisionDetection = true

    lineNode = SKShapeNode()
    lineNode.physicsBody = linePhysicsBody
    lineNode.name = "drawingLine"
    lineNode.path = linePath
    lineNode.lineWidth = 5.0
    lineNode.strokeColor = UIColor.redColor()
    lineNode.glowWidth = 1.0

    self.addChild(lineNode)
}

func didBeginContact(contact: SKPhysicsContact) {

    println("contact \(++tempCounter)")
    println("bitmask1: \(contact.bodyA.categoryBitMask)")
    println("bitmask2: \(contact.bodyA.categoryBitMask)")
}

1 个答案:

答案 0 :(得分:1)

对于问题1:

你的线物理主体的大小为0.你必须至少创建一个代表该线的小矩形。其他没有碰撞。

对于问题2:

func didBeginContact(contact: SKPhysicsContact) {

    println("contact \(++tempCounter)")
    println("bitmask1: \(contact.bodyA.categoryBitMask)")
    println("bitmask2: \(contact.bodyA.categoryBitMask)")
}

这是一个错字。您必须将bodyB用于bitmask2