当两个手指在屏幕上时,应用程序崩溃,触摸开始,触摸移动

时间:2017-03-03 08:32:06

标签: swift sprite-kit

我不确定发生了什么,所以我无法正确地向你描述,我制作了一个应用程序,用拖动用户手指划线,它是一个精灵套件游戏所以我使用了touchesBegan和touchesMoved,所以如果我将手指放在屏幕上而我正在绘制另一条线时游戏崩溃会发生什么。我正在寻找的是一种忽略第二次触摸直到第一次触摸的方式。我的游戏从触摸的开始位置到触摸结束时的结束位置画一条线 这是我的触摸函数中的代码

var lineNode = SKShapeNode()

        override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch: AnyObject in touches{
            positionOfStartTouch = touch.location(in: self)
            lastPoint = touch.location(in: self)
            firstPoint = touch.location(in: self)
        }
        let pathToDraw = CGMutablePath()
        print(pathToDraw.isEmpty)
        pathToDraw.move(to: CGPoint(x: firstPoint.x, y: firstPoint.y))
        if frame.width == 375 {
            lineNode.lineWidth = 4
        }else if frame.width == 414 {
            lineNode.lineWidth = 6
        }else if frame.width == 768 {
            lineNode.lineWidth = 8
        }
        lineNode.strokeColor = UIColor.white
        lineNode.name = "Line"
        lineNode.zPosition = 100000
        lineNode.path = pathToDraw
        self.addChild(lineNode)
        shapeNodes.append(lineNode)
}
}
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch: AnyObject in touches{
            positionInScene = touch.location(in: self)
        }
        let pathToDraw = lineNode.path as! CGMutablePath
        lineNode.removeFromParent()
        pathToDraw.move(to: CGPoint(x: firstPoint.x, y: firstPoint.y))
        pathToDraw.addLine(to: CGPoint(x: positionInScene.x, y: positionInScene.y))
        lineNode.path = pathToDraw
        shapeNodes.append(lineNode)
        self.addChild(lineNode)
        firstPoint = positionInScene
    }

1 个答案:

答案 0 :(得分:2)

该节点只能有一个父节点。您正尝试多次添加lineNode场景。试试这个:

 override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch: AnyObject in touches{
        positionInScene = touch.location(in: self)
    }
    let pathToDraw = lineNode.path as! CGMutablePath
    lineNode.removeFromParent()
    pathToDraw.move(to: CGPoint(x: firstPoint.x, y: firstPoint.y))
    pathToDraw.addLine(to: CGPoint(x: positionInScene.x, y: positionInScene.y))
    lineNode.path = pathToDraw

    if let copy = lineNode.copy() as? SKShapeNode {
        shapeNodes.append(copy)
        self.addChild(copy)
    }

    firstPoint = positionInScene

}

touchesBegan中执行相同操作。当然,我并没有考虑到多次触摸发生时应该发生什么的逻辑。我只是指出错误的位置以及应用程序崩溃的原因。

相关问题