我将 SKSpritenode(在 Swift 中)子类化以创建彩色 block ,然后可以在场景中拖动这些 block 。子类是 SoundNode。
import SpriteKit
class SoundNode: SKSpriteNode {
init() {
super.init(texture: nil, color: UIColor.blue, size: CGSize(width: 100, height: 100))
self.isUserInteractionEnabled = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
print("touch began")
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
print("touches moved")
guard let touch = touches.first else {
return
}
let touchLocation = touch.location(in: self)
self.position = touchLocation
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
print("touch ended")
}
}
在 GameScene.swift 中
import SpriteKit
class GameScene: SKScene {
override func didMove(to view: SKView) {
addSoundBlock()
}
func addSoundBlock() {
let soundBlock = SoundNode()
soundBlock.position = CGPoint(x: 800, y: 800)
addChild(soundBlock)
}
}
这有点管用。
添加了 soundBlock,可以在场景中拖动。但它会闪烁,有时会消失。 我在 touchesMoved 中尝试了其他方法,但没有一种方法会影响抖动。
如果我不对 touchesBegan、touchesMoved、touchesEnded 进行子类化,并在 GameScene 中实现这些 Action ,那么拖动就会变得流畅。但 future 的计划取决于能否对这些进行子类化。
Xcode 8、Swift 3、iOS10
最佳答案
我创建了一个类方法来处理 SKSpriteNode 的子类的移动,在我的例子中是“Player”,并将触摸的位置传递给它在 GameScene.swift 中。
Player.swift 中的类方法声明:
func movePlayer(location: CGPoint) {
//movement code
}
调用GameScene.swift中的函数:
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let location = touches.first?.location(in: self) else { return }
player.movePlayer(location: location)
}
我想更干净一些。并允许进一步子类化。
关于ios - SpriteKit touchesMoved 在 SKSpritenode 的子类中使用时不稳定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40793998/