我正在尝试在SKShapeNode
(一个圆形节点)和SKShapeNode
(一个方形节点)之间实现碰撞检测,就像应用程序“ Snake VS Blocks”一样。
以下是我创建节点的代码段
private func addSnake() {
snake = SKShapeNode(circleOfRadius: Constants.snakeRadius)
snake.fillColor = Constants.snakeColor
let snakeXPosition = (Helper.getScreenWidth() / 2.0) - Constants.snakeRadius
snake.position = CGPoint(x: snakeXPosition, y: size.height * 0.3)
snake.physicsBody = SKPhysicsBody(rectangleOf: snake.frame.size)
snake.physicsBody?.isDynamic = false
snake.physicsBody?.categoryBitMask = PhysicsCategory.snake
snake.physicsBody?.contactTestBitMask = PhysicsCategory.block
snake.physicsBody?.collisionBitMask = PhysicsCategory.none
snake.name = "Snake"
addChild(snake)
}
func addBlocks() {
for index in 0...(blockCount-1) {
let hasBlock = getRandomBool()
if hasBlock {
let block = getBlock(for: index)
block.fillColor = .red
addChild(block)
let actionMove = getBlockMoveAction(for: block, atIndex: index)
let actionMoveDone = SKAction.removeFromParent()
block.run(SKAction.sequence([actionMove, actionMoveDone]))
}
}
}
func getBlockMoveAction(for block: SKShapeNode, atIndex: Int) -> SKAction {
return SKAction.move(to: CGPoint(x: CGFloat(atIndex) * width, y: -block.frame.size.height),
duration: TimeInterval(blockMovementDuration))
}
func getBlock(for index: Int) -> SKShapeNode {
let rect = CGRect(x: 0, y: 0, width: width, height: width)
let block = SKShapeNode(rect: rect, cornerRadius: Constants.blockCornerRadius)
block.name = "Block"
block.position = CGPoint(x: CGFloat(index) * width, y: (Helper.getScreenHeight() + width))
block.physicsBody = SKPhysicsBody(rectangleOf: block.frame.size)
block.physicsBody?.isDynamic = false
block.physicsBody?.categoryBitMask = PhysicsCategory.block
block.physicsBody?.contactTestBitMask = PhysicsCategory.snake
block.physicsBody?.collisionBitMask = PhysicsCategory.none
return block
}
func getRandomBool() -> Bool {
return arc4random_uniform(2) == 0
}
下面是上面代码的结果图像:
我的第一个问题是,我不知道为什么,但是当我启用skview以显示物理时,
view.showsPhysics = true
我发现我的视野不正确
第二,我也确认要与代表联系
physicsWorld.contactDelegate = self
但是我的
didBegin(_ contact: SKPhysicsContact)
没有被触发
extension GameScene: SKPhysicsContactDelegate {
func didBegin(_ contact: SKPhysicsContact) {
var firstBody: SKPhysicsBody
var secondBody: SKPhysicsBody
if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
firstBody = contact.bodyA //snake
secondBody = contact.bodyB //block
} else {
firstBody = contact.bodyB //block
secondBody = contact.bodyA //snake
}
if ((firstBody.categoryBitMask & PhysicsCategory.snake != 0) &&
(secondBody.categoryBitMask & PhysicsCategory.block != 0)) {
if let snake = firstBody.node as? SKShapeNode,
let block = secondBody.node as? SKShapeNode {
snakeDidCollideWithBlock(snake: snake, block: block)
}
}
}
func snakeDidCollideWithBlock(snake: SKShapeNode, block: SKShapeNode) {
print("Hit")
block.removeFromParent()
}
}
我在stackoverflow中经历了其他问题,以寻找类似的问题,但是没有找到任何解决方案。
答案 0 :(得分:2)
“ isDynamic”之一或全部为true。否则,它们的行为就像墙一样,从不参与物理模拟。