Ios 无法检测到掉落的SKShapeNode//SpriteKite上的触摸
我在GameSecene.swift中有一个炸弹产卵器,它将SKShapeNodes添加到场景中。每个SKShapeNode都是一个物理对象,下落时名称设置为“bomb”。我想检测用户何时触摸这些节点(在秋季中期使用TouchesBegind),但它不起作用。我做错了什么Ios 无法检测到掉落的SKShapeNode//SpriteKite上的触摸,ios,swift,sprite-kit,sknode,Ios,Swift,Sprite Kit,Sknode,我在GameSecene.swift中有一个炸弹产卵器,它将SKShapeNodes添加到场景中。每个SKShapeNode都是一个物理对象,下落时名称设置为“bomb”。我想检测用户何时触摸这些节点(在秋季中期使用TouchesBegind),但它不起作用。我做错了什么 // Bomb Spawner Function func spawnBomb() { let bombHeight = 80 let bomgWidth = 40 // Define Bomb
// 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")
}
}
}
override func touchsbegind(touch:Set,带有事件:UIEvent?){
让触摸:UITouch=touch.first!
let positionInScene=触摸位置(in:self)
让touchedNode=self.atPoint(positionInScene)
如果let name=touchedNode.name
{
如果名称==“炸弹”
{
打印(“炸弹接触”)
}
}
}
我怀疑您的问题源于atPoint返回SKNode这一事实。有两种方法可以获取最顶端的节点:
if atPoint(touch.location(in: self)) == childNode(withName: "bomb"){
//run your code
}
对于单个节点来说,这很好。就个人而言,我喜欢使用子类,所以我会使用
类炸弹:SKShapeNode
只需看看我触摸下的最上面的节点是否可以投射到炸弹上
if let bomb = atPoint(touch.location(in: self)) as? Bomb {
//...
}
这使您可以将典型设置移动到子类中,并使代码总体上更具可读性 我不是游戏专家,我从来没有这样做过。但我想你应该在每个炸弹对象被实例化时为其添加一个触摸手势识别器。我想这应该能帮助你找到答案。我重写了整个过程并使用了这个方案。我不知道为什么它以前不起作用。