我正在使用SpriteKit创建一个Swift Playground但无法使碰撞检测工作。我已经在StackOverFlow上阅读了有关此问题的所有帖子,但没有一个帖子解决了我的问题。以下是我的代码:
public class MyScene: SKScene, SKPhysicsContactDelegate {
var node: SKSpriteNode?
var touchedNodeCreator: Timer?
let nodeCategory : UInt32 = 0x1 << 1
let touchedNodeCategory : UInt32 = 0x1 << 2
var score = 0
public override func didMove(to view: SKView) {
//Setup
physicsWorld.contactDelegate = self
self.backgroundColor =
UIColor(red:0.60, green:0.88, blue:1.00, alpha:1.0)
//node
node = SKSpriteNode(imageNamed: "node")
node!.setScale(0.175)
node!.physicsBody? = SKPhysicsBody(rectangleOf: node!.size)
node!.physicsBody?.categoryBitMask = nodeCategory
node!.physicsBody?.contactTestBitMask = touchedNodeCategory
node!.physicsBody?.collisionBitMask = floorCategory
floor.physicsBody?.categoryBitMask = floorCategory
floor.physicsBody?.collisionBitMask = nodeCategory
let nodeStartingPos = CGPoint(x: node!.size.width / 2 + 25, y: self.size.height / 5 + node!.size.height / 2)
node!.position = nodeStartingPos
addChild(node!)
//Create touchedNode Timer
touchedNodeCreator = Timer.scheduledTimer(withTimeInterval: 3, repeats: true) { (timer) in
self.createtouchedNode()
}
}
func createtouchedNode() {
let touchedNode = SKSpriteNode(imageNamed: "otherNode")
touchedNode.setScale(0.2)
touchedNode.name = "TouchedNode"
touchedNode.physicsBody? = SKPhysicsBody(rectangleOf: touchedNode.size)
touchedNode.physicsBody?.affectedByGravity = false
let maxY = self.size.height / 1 - touchedNode.size.height / 2
let minY = self.size.height / 5 + 25
let rangeY = maxY - minY
let y = maxY - CGFloat(arc4random_uniform(UInt32(rangeY)))
let touchedNodeStartingPos = CGPoint(x: self.size.width + 20, y: y)
touchedNode.position = touchedNodeStartingPos
touchedNode.physicsBody?.categoryBitMask = touchedNodeCategory
touchedNode.physicsBody?.contactTestBitMask = nodeCategory
addChild(touchedNode)
let moveLeft = SKAction.moveBy(x: -size.width - touchedNode.size.width, y: 0, duration: 3)
let remove = SKAction.removeFromParent()
let sequence = SKAction.sequence([moveLeft, remove])
touchedNode.run(sequence)
}
public func didBegin(_ contact: SKPhysicsContact) {
print("Began")
if contact.bodyA.categoryBitMask == touchedNodeCategory {
contact.bodyA.node?.removeFromParent()
score += 1
print(score)
} else if contact.bodyB.categoryBitMask == touchedNodeCategory {
contact.bodyB.node?.removeFromParent()
score += 1
print(score)
}
}
请记住,我省略了很多代码,主要是在检测到任何触摸时移动节点的代码。
如果你们能帮我解决这个问题,我将不胜感激。谢谢!