我一直在研究一個遊戲,每當我的測試節點與我的校驗節點聯繫時都必須執行測試。由於這兩個節點是檢查遊戲中碰撞的唯一節點,我決定使用這種方法來啓動我的測試。Swift碰撞不起作用。我認爲didBeginContact中的代碼有問題
問題是我一直有麻煩讓我的碰撞工作時,2節點物理交叉。
當前代碼將移動測試方塊直到它到達校驗方塊,但是現在當它們相遇時沒有任何反應。
我錯過了什麼嗎?任何幫助將不勝感激。謝謝。
import SpriteKit
class GameScene: SKScene, SKPhysicsContactDelegate {
var test:SKSpriteNode!
var testTexture = SKTexture(imageNamed: "redsquare.png")
var check:SKSpriteNode!
var checkTexture = SKTexture(imageNamed: "bluesquare.png")
var moving:SKNode!
let testCategory: UInt32 = 1 << 0
let checkCategory: UInt32 = 1 << 2
override func didMoveToView(view: SKView) {
/* Setup your scene here */
self.physicsWorld.gravity = CGVectorMake(0.0, 0.0)
self.physicsWorld.contactDelegate = self
moving = SKNode()
self.addChild(moving)
//create test block
test = SKSpriteNode(texture: testTexture)
test.xScale = 0.1
test.yScale = 0.1
test.position = CGPointMake(0, self.frame.height - test.size.height)
test.physicsBody = SKPhysicsBody(rectangleOfSize: test.size)
test.physicsBody?.dynamic = false
test.physicsBody?.categoryBitMask = testCategory
test.physicsBody?.collisionBitMask = checkCategory
test.physicsBody?.contactTestBitMask = checkCategory
self.addChild(test)
//creates check block
check = SKSpriteNode(texture: checkTexture)
check.xScale = 0.1
check.yScale = 0.1
check.position = CGPointMake(self.frame.width, self.frame.height - check.size.height)
check.physicsBody = SKPhysicsBody(rectangleOfSize: check.size)
check.physicsBody?.dynamic = false
check.physicsBody?.categoryBitMask = checkCategory
check.physicsBody?.collisionBitMask = testCategory
check.physicsBody?.contactTestBitMask = testCategory
self.addChild(check)
// move action
let actionMove = SKAction.moveToX(self.frame.width, duration: 1.5)
let actionMoveDone = SKAction.moveToX(0, duration: 0)
let moveForever = SKAction.repeatActionForever(SKAction.sequence([actionMove,actionMoveDone]))
test.runAction(moveForever)
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
/* Called when a touch begins */
for touch: AnyObject in touches {
}
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
func didBeginContact(contact: SKPhysicsContact) {
// help here!
var firstBody:SKPhysicsBody
var secondBody:SKPhysicsBody
if (contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask){
firstBody = contact.bodyA
secondBody = contact.bodyB
}
else{
firstBody = contact.bodyB
secondBody = contact.bodyA
}
if((firstBody.categoryBitMask & testCategory) != 0 && (secondBody.categoryBitMask & checkCategory) != 0){
println("contact!")
}
}
}
更新:我想通了。我將兩個節點都設置爲false。當我將其中的一個更改爲true時,聯繫人正常工作。我不知道爲什麼。 – 2015-02-12 06:37:29