【发布时间】:2017-11-20 19:24:17
【问题描述】:
我有一个应用程序,它每 1 秒在屏幕上生成一个球。现在,我希望用户触摸那些使它们消失的球(removeFromParent())。据我了解,我必须通过 touchesBegan 设置触摸功能,我这样做了,这是我的代码:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch: AnyObject in touches{
let positionOfTouch = touch.location(in: self)
enumerateChildNodes(withName: "BALL") { (node: SKNode, nil) in
if positionOfTouch == node.position {
print("just touched the ball")
}
else{
print("error")
}
}
}
问题是,当我触摸屏幕/球时,控制台打印 error 而不是 just touch the ball,这意味着我的代码不起作用。此外,控制台将错误消息打印为我认为的球数。我不明白我做错了什么以及如何真正设置此功能。 这是我的 createBall 函数,它从我的 BallNode 类(类型 SKShapeNode)中实现:
func createBall(){
let ball = BallNode(radius: 65)
print(ball.Name)
print(ball._subName!)
ball.position.y = ((frame.size.height) - 200)
let ballXPosition = arc4random_uniform(UInt32(frame.size.width)) // set the ball a randon position from the top of the screen
ball.position.x = CGFloat(ballXPosition)
ball.physicsBody?.categoryBitMask = PhysicsCategory.ball // ball's category bitMask
ball.physicsBody?.collisionBitMask = PhysicsCategory.ball // prevent objects from intersecting
ball.physicsBody?.contactTestBitMask = PhysicsCategory.topBorder // when need to know if two objects touch each other
addChild(ball)
}
你能帮我解决这个问题吗?因为我对 swift 很陌生,所以我也想得到一些关于这种触摸检测的解释(以及一般的触摸 - 苹果文档很差)。
【问题讨论】:
-
这里列出了一些替代选项:stackoverflow.com/q/27922198/6658553
标签: swift sprite-kit uitouch touchesbegan