Как определить, был ли затронут SKSpriteNode
Я пытаюсь определить, был ли затронут мой спрайт node, и я не знаю, с чего начать.
let Pineapple = SKSpriteNode(imageNamed: "Pineappleimg")
Pineapple.userInteractionEnabled = true
Pineapple.position = CGPoint(x: CGRectGetMidX(self.frame) - 200, y: CGRectGetMidY(self.frame));
self.addChild(Pineapple)
Ответы
Ответ 1
Сначала установите для свойства name
значение SKSpriteNode
в строку.
pineapple.name = "pineapple"
pineapple.userInteractionEnabled = false
то в touchesBegan
функция в Scene
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
let touch:UITouch = touches.anyObject()! as UITouch
let positionInScene = touch.locationInNode(self)
let touchedNode = self.nodeAtPoint(positionInScene)
if let name = touchedNode.name
{
if name == "pineapple"
{
print("Touched")
}
}
}
Это один из способов сделать это.
Вы также можете подклассом SKSpriteNode
и переопределить touchesBegan
внутри него.
class TouchableSpriteNode : SKSpriteNode
{
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
print("touched")
}
}
Тогда do
let pineapple = TouchableSpriteNode(imageNamed: "Pineappleimg")
pineapple.userInteractionEnabled = true
pineapple.position = CGPoint(x: CGRectGetMidX(self.frame) - 200, y: CGRectGetMidY(self.frame));
self.addChild(pineapple)
Ответ 2
Если вы ищете только несколько узлов, которые могут быть затронуты (например, метки "Продолжить" или "Выйти" в пользовательском интерфейсе игры), это может быть альтернативным, но очень простым решением:
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
let touch = touches.first!
if myNode.containsPoint(touch.locationInNode(self)) {
print("touched")
}
}
Ответ 3
Обновление для версии Swift Swift 3.0.2 (swiftlang-800.0.63 clang-800.0.42.1) и версия XCode 8.2.1 (8C1002):
Значение типа 'Set' не имеет члена ' anyObject'
' locationInNode' переименован в 'location (in:)'
' nodeAtPoint' был переименован в 'atPoint (_:)'
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in: self)
let node : SKNode = self.atPoint(location)
if node.name == "myNodeName" {
print("Hello")
}
}
}
Ответ 4
Это обнаружит прикосновения в Xcode 9.2 Swift 4.0
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
{
let touch:UITouch = touches.first!
let positionInScene = touch.location(in: self)
let touchedNode = self.atPoint(positionInScene)
if let name = touchedNode.name
{
if name == "playLbl"
{
print("playLbl Touched")
}
}
}
Ответ 5
Swift 3 ответ, который встраивает сенсорные функции в подкласс SKSpriteNode
:
class SpriteSub: SKSpriteNode {
init() {
super.init(texture: nil, color: UIColor.red, size: CGSize(width: 50, height: 50))
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!")
}
}
Ответ 6
Внедрить метод touchesBegan
, который вызывается при начале касания. Вы также можете сделать это в touchesEnded
.
override func touchesBegan(touches: NSSet, withEvent event: UIEvent)
{
let touch = touches.anyObject() as UITouch
let location = touch.locationInNode(self)
let nodes = self.nodesAtPoint(location)
for node in nodes
{
if node.name == "youNodeName"
{
// Node tapped
// Do something
break
}
}
}
Ответ 7
Используйте этот фрагмент кода для обнаружения касания SKSpriteNode
if(nodeAtPoint(location) == node){
}
Ответ 8
Обновление для Swift 3.0 и XCode 7.3.1. У меня есть SKShapeNode, который я получил для нового класса и вставил его в Сцена. Когда я хочу обнаружить этот объект, я проверяю следующее:
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch in touches {
let location = touch.locationInNode(self)
let nodes = self.nodesAtPoint(location)
for node in nodes
{
if node is SKNodeDerivedNode
{
NSLog("Touch a SKNodeDerivedNode")
break
}
}
}
}
Ответ 9
Вот способ, которым я пользуюсь в Swift 4, чтобы определить, есть ли прикосновение в узле определенного типа:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else {
return
}
let touchPosition = touch.location(in: self)
let touchedNodes = nodes(at: touchPosition)
for node in touchedNodes {
if let nodoTouched = node as? YourNodeType {
// touched!
}
}
}
Ответ 10
Если ваш спрайт до сих пор не работает даже после SKSpriteNode
подкласса SKSpriteNode
, вы, скорее всего, забыли добавить node.isUserInteractionEnabled = true
при его инициализации!
Это позволяет touchesBegan(_:with:)
, поскольку теперь вы можете взаимодействовать с узлом.
Пример:
node = MySprite(texture: texture, size: size)
node.isUserInteractionEnabled = true