ios - 在下降的 SKShapeNode 上无法检测到触摸 // SpriteKite
问题描述
我在 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")
}
}
}
解决方案
我怀疑您的问题源于 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 {
//...
}
这使您可以将炸弹典型设置移动到子类中,并使整体代码更具可读性。
推荐阅读
- javascript - 拒绝在 Electron 中设置不安全的标头错误
- java - 编写布局管理器对象后我的应用程序崩溃
- javascript - Puppeteer - 在 div 内向下滚动(一个站点上有多个滚动条)
- asp.net - 在 Visual Studio 上使用 VB.NET
- ios - 如何从另一个类引用已经创建的视图控制器?
- java - Spring Boot Lazy Loading OrderLine items on Orders GetMapping Request
- azure - 将 VSTS 请求创建为未分配时的通知
- c# - 使用 VSTO 在 Word 文档的每一页上插入一个矩形
- javascript - 我们能否创建一个接受组件并为其添加和应用额外道具的 HoC 或组合?
- python - Python 执行时间