在两个函数之间传递变量

时间:2020-04-20 17:58:16

标签: swift sprite-kit

以下是相关代码:

func touchLocationAngle() {
        func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
            for touch in touches{
                var touchLocation = touch.location(in: self)
                var angle1 = atan2(1SpriteNode.position.y - touchLocation.y , 1SpriteNode.position.x - touchLocation.x)
                var angle = angle1 - CGFloat(Double.pi / 1)
            }
        }
    }

    func moveToTouchLocation() {

    }

我想从第一个函数中获取angle变量,然后在第二个函数中使用。我不想将变量设为全局。我看过google和youtube,但是每当我使用它们的代码时,它们都会显示错误。

1 个答案:

答案 0 :(得分:0)

几件事,我可以根据需要编辑答案,但是第一个功能的目的是什么?据我所知,这是一个包含其他功能的功能,它通过触摸来实现。但是我也注意到angle在每个循环周期中也会被覆盖,只剩下最后一次触摸的角度。我的回答是刺痛我想要的东西,但是请弄清楚是否不是。

您将要在第一个函数中返回角度,当前第一个函数没有返回值。然后,您将要调用第一个函数,并将值传递给第二个,例如

func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches{
        var touchLocation = touch.location(in: self)
        var angle1 = atan2(1SpriteNode.position.y - touchLocation.y , 1SpriteNode.position.x - touchLocation.x)
        var angle = angle1 - CGFloat(Double.pi / 1)
        moveToTouchLocation(angle)
    }
}

func moveToTouchLocation(angle: CGFloat) {
    // whatever you want to do here.
}