我有一个自定义类,它是SKNode类型,其中又包含多个SKSpriteNode。有没有办法在我的游戏场景中检测到对这些子节点SKSpriteNode的触摸?
我正在使用Swift语言。
我有一个自定义类,它是SKNode类型,其中又包含多个SKSpriteNode。有没有办法在我的游戏场景中检测到对这些子节点SKSpriteNode的触摸?
我正在使用Swift语言。
override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
let touch = touches.anyObject() as UITouch
let touchLocation = touch.locationInNode(self)
if([yourSprite containsPoint: touchLocation])
{
//sprite contains touch
}
}
来源: http://www.raywenderlich.com/84434/sprite-kit-swift-tutorial-beginners
这篇教程介绍了如何使用SpriteKit框架和Swift编程语言创建2D游戏。SpriteKit是一个由苹果公司开发的游戏引擎,可以帮助开发人员轻松地创建动画、物理效果等游戏元素。override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
guard let scene = self.overlaySKScene else {
return
}
let touch = touches.first!
let viewTouchLocation = touch.locationInView(self)
let sceneTouchPoint = scene .convertPointFromView(viewTouchLocation)
let touchedNode = scene.nodeAtPoint(sceneTouchPoint)
if (touchedNode.name == "Play") {
print("play")
}
}
isUserInteractionEnabled = true
然后,当然,根据您的需要覆盖touchesBegan方法。
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {}
delegate
定义协议和属性,并将场景设置为其代理。
e.g:
final class GameScene: SKScene {
private let childNode = ChildNode()
override func didMove(to view: SKView) {
addChild(childNode)
childNode.delegate = self
}
}
extension GameScene: TouchDelegate {}
protocol TouchDelegate {
func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
}
final class ChildNode: SKSpriteNode {
var delegate: TouchDelegate?
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
delegate?.touchesBegan(touches, with: event)
}
}