在swift中使用sprite工具包触摸角矩形。代码将运行,但不显示任何矩形

时间:2017-01-24 01:33:31

标签: swift sprite-kit skspritenode

我想添加一个带有用户第一次触摸的角落的矩形,以及用户抬起的另一个角落。我还想在用户拖动手指时显示矩形。

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches{
        let position1 = touch.location(in: self)
        var x1 = position1.x
        var y1 = position1.y


        func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches{
        let position2 = touch.location(in: self)
        var x2 = position2.x
        var y2 = position2.y

        var originX = min(x1,x2)
        var originY = min(y1,y2)
        var cornerX = max(x1,x2)
        var cornerY = max(y1,y2)
        var rect_width = cornerX - originX
        var rect_height = cornerY - originY

        var rect_con = CGRect(x: originX, y:originY, width: rect_width, height: rect_height)

        var box = SKShapeNode(rect: rect_con)
    }
}

2 个答案:

答案 0 :(得分:2)

首先,如果你只是在一个矩形之后,你最好只用一个SKSpriteNode来做这个,然后用它来缩放它:

https://developer.apple.com/reference/spritekit/skspritenode/1645445-scale

其次,为了将来参考,SKShapeNode是CAShapeLayer的一半(或更少)完整转换为非常原始的绘图工具。它根本不擅长动态绘图。

在触摸点设置SKSpriteNode矩形的锚点,并缩放到touchesMoved的x和y。您可能需要对负值进行一些转换,因为这是从笛卡尔坐标中的原点开始的。

答案 1 :(得分:0)

在我看来,你的touchesEnded函数是从touchesStart函数中声明的,因为它在类范围内是不可见的,然后永远不会被调用。它看起来应该更像(未经测试):

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches{
    let position1 = touch.location(in: self)
    var x1 = position1.x
    var y1 = position1.y
    }
}

func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches{
    let position2 = touch.location(in: self)
    var x2 = position2.x
    var y2 = position2.y

    var originX = min(x1,x2)
    var originY = min(y1,y2)
    var cornerX = max(x1,x2)
    var cornerY = max(y1,y2)
    var rect_width = cornerX - originX
    var rect_height = cornerY - originY

    var rect_con = CGRect(x: originX, y:originY, width: rect_width, height: rect_height)

    var box = SKShapeNode(rect: rect_con)
}
}