【Swift/SpriteKit】SKSceneでタッチイベント
タッチイベント時にしょっちゅう使いそうなことをメモ。
タッチ感知の種類
// 画面に指が触れた瞬間の処理 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { // code } // 指が触れたまま動かした時の処理 override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { // code } // 画面から指が離れた時の処理 override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { // code }
タッチ情報を取得
取得した情報(オプショナル)をアンラップする
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { // nilチェックとアンラップ guard let touch = touches.first else { return } }
タッチされた位置
画面上の座標を取得
let touchedPos = touch.location(in: self)
タッチされた位置のノードを取得
let node = self.atPoint(touchedPos)
特定のノードをタッチした時の処理
「このオブジェクトをタッチしたらこうしたい」という時の処理。
// タッチ位置を取得 let touchedPos = touch.location(in: self) // タッチした位置にあるノードを取得 let node = self.atPoint(touchedPos) // タッチされたノードが任意のオブジェクトだった時 if node == self.sampleSprite { // code }