拖放-自定义SKSpriteNode位置问题

时间:2019-09-05 08:16:06

标签: swift sprite-kit

我在我的游戏中使用的是自定义SKSpriteNode,玩家可以将其拖放到自己希望的位置。

我的自定义节点由文件DraggableNode.swift中的以下代码组成:

    class DraggableNode : SKSpriteNode {

    var nodeSelected : SKNode?

    init() {
        let texture = SKTexture(imageNamed: "draggableNode_1")
        super.init(texture: texture, color: UIColor.white, size: texture.size())
        self.isUserInteractionEnabled = true
        self.zPosition = 1
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch = touches.first {
            let location = touch.location(in: self)

            let touchedNodes = self.nodes(at: location)
            for node in touchedNodes.reversed() {
                nodeSelected = node
            }
        }
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch = touches.first, let node = self.nodeSelected {
            let touchLocation = touch.location(in: self)
            node.position = touchLocation
        }
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        nodeSelected = nil
    }

    override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
        nodeSelected = nil
    }
}

在我的GameScene.swift中,以这种方式添加自定义节点:

let node = DraggableNode()
node.position = CGPoint(x: randomX, y: randomY)
self.addChild(node)

现在,问题是当我开始拖动节点时,它全都跳了起来,并被放置在一个完全随机的位置-有时甚至超出了屏幕区域。

我想知道问题是否在于它是从SKSpriteNode继承的自定义节点的事实吗?

如果有人能指出我正确的方向,我将是一个快乐的人:-)

0 个答案:

没有答案