精灵套件 - 当触摸移动到精灵上但实际上并没有在精灵上开始时,如何捕捉事件



在SpriteKit中,我想在触摸移动到精灵上时捕捉事件,但实际上还没有在这个精灵上开始,而是在另一块SKScene上开始。

我可以捕捉触摸在 SKSpriteNode A 内部开始,如果触摸开始在它上面然后拖过它,但当触摸在另一个节点 - B - 然后拖过我的节点 - A 时,我不能

试试这个:对不起,这是快速的..但是您可以轻松地在 obj c 中做同样的事情

import SpriteKit
class GameScene: SKScene {
    let sprite = SKSpriteNode(color: SKColor.redColor(), size: CGSizeMake(100, 100))
    var startedOutsideSprite = true
    override init(size: CGSize) {
        super.init(size: size)
        sprite.position = CGPointMake(size.width/2, size.height/2)
        addChild(sprite)
    }
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        if let touch = touches.first {
            let location = touch.locationInNode(self)
            if !sprite.containsPoint(location) {
                startedOutsideSprite = true
            }
        }
    }
    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
        if let touch = touches.first {
            let location = touch.locationInNode(self)
            if sprite.containsPoint(location) && startedOutsideSprite {
                print("yayyy")
                // your code here
            }
        }
    }
    override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
        startedOutsideSprite = false
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

谢谢@Christian W.但是我现在有一个更简单的解决方案,尽管这不是我实际上想到的:只需将其放入 Scene 中并捕获触摸移动到其中,其中包含以下代码:

SKNode * draggedOverNode = [self nodeAtPoint:location];
[draggedOverNode touchesMoved:touches withEvent:event];

并在该对象中实现 touchesMoving 函数,该函数实际上扩展了 SKNode(您的大多数类都会这样做(。

最新更新