我无法使用精灵套件让标准精灵具有切换功能。我不想使用UIButton。
我尝试在覆盖功能触摸中链接代码开始了,但我被难住了。我根本不习惯快速,事实证明,带有spritekit的按钮非常困难。
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if (!isEnabled) {
return
}
isSelected = true
if (targetTouchDown != nil && targetTouchDown!.respondsToSelector(actionTouchDown!)) {
UIApplication.sharedApplication().sendAction(actionTouchDown!, to: targetTouchDown, from: self, forEvent: nil)
}
}
我想点击一个精灵,让它改变颜色并将数据发送到两个不同的数组。我有使用其他语言的数组的经验,所以我不需要帮助,只需要接受点击即可。
Warner创建了一个子类并使其可触摸。
import SpriteKit
protocol touchMe: NSObjectProtocol {
func spriteTouched(box: TouchableSprite)
}
class TouchableSprite: SKSpriteNode {
weak var delegate: touchMe!
override init(texture: SKTexture?, color: UIColor, size: CGSize) {
super.init(texture: texture, color: color, size: size)
self.isUserInteractionEnabled = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:)has not been implemented")
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
delegate.spriteTouched(box: self)
}
}
并在您的代码中调用它...
let restart = TouchableSprite(imageNamed: "mine")
restart.delegate = self
您需要让您的类确认 touchMe 协议并添加所需的方法来确认它。
class ViewController, touchMe
必需的方法。
func spriteTouched(box: TouchableSprite) {
print("sprite touched")
}
使用touchesBegan()
(没有理由不这样做(,那么你需要意识到每当触摸屏幕时都会触发。因此,您接下来要做的就是获取触摸的位置(坐标(,看看那里是否有精灵:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let touchedSprite = selectNodeForTouch(touch.location(in: self))
if let sprite= touchedSprite {
sprite.changeColour()
sprite.sendData(to: array1)
sprite.senddata(to: array2)
}
}
}
// Returns the sprite where the user touched the screen or nil if no sprite there
func selectNodeForTouch(_ touchLocation: CGPoint) -> SKSpriteNode? {
let touchedNode = self.atPoint(touchLocation) // Get the node at the touch point
return (touchedNode is SKSpriteNode) ? (touchedNode as! SKSpriteNode) : nil
}
因此,我们查看触摸位置,获取该位置的节点,如果节点是 SKSpriteNode,我们在其上运行changeColour()
和sendData()
函数。