【发布时间】:2018-06-23 20:38:59
【问题描述】:
我在 GameScene.swift 中有一个炸弹生成器,它将 SKShapeNodes 添加到场景中。每个 SKShapeNode 都是一个落下的物理对象,名称设置为“bomb”。我想检测用户何时触摸这些节点(中秋使用 touchesBegan),但它不起作用。我做错了什么?
// Bomb Spawner Function
func spawnBomb() {
let bombHeight = 80
let bomgWidth = 40
// Define Bomb
let bomb = SKShapeNode(rectOf: CGSize(width: bomgWidth,
height: bombHeight))
bomb.name = "bomb"
bomb.zPosition = 10
bomb.isUserInteractionEnabled = true
bomb.position = CGPoint(x: size.width / 2, y: size.height / 2)
bomb.fillColor = SKColor.blue
// Add Physics Body
bomb.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: bomgWidth,
height: bombHeight))
// Determine Random Position
let randomPosition = abs(CGFloat(random.nextInt()).truncatingRemainder(dividingBy: size.width))
bomb.position = CGPoint(x: randomPosition, y: size.height)
// Add Category BitMask
bomb.physicsBody?.categoryBitMask = BombCategory
bomb.physicsBody?.contactTestBitMask = WorldFrameCategory
// Add to the scene
addChild(bomb)
}
触摸检测
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch:UITouch = touches.first!
let positionInScene = touch.location(in: self)
let touchedNode = self.atPoint(positionInScene)
if let name = touchedNode.name
{
if name == "bomb"
{
print("bomb Touched")
}
}
}
【问题讨论】:
-
我不是游戏专家,我从来没有这样做过。但我认为您想在实例化每个炸弹对象时为其添加一个触摸手势识别器。
-
我认为This RayWenderlich Tutorial 应该可以帮助您解决问题。
标签: ios swift sprite-kit sknode