如何全球存储价值?

时间:2017-01-27 05:04:46

标签: swift sprite-kit 2d 2d-games

代码将存储x1和y1变量,但只要touchesEnded函数开始,它们就会恢复到原来的0.0值。我希望在touchesBegan函数结束后保留​​这些值。我该如何存储这些值?

var x1: CGFloat = 0.0
var y1: CGFloat = 0.0
var x2: CGFloat = 0.0
var y2: CGFloat = 0.0

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

//touch ends
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches {
        print(x1,y1)
        let location2 = touch.location(in: self)
        let x2 = location2.x
        let y2 = location2.y
        let originX = min(x1,x2)
        let originY = min(y1,y2)
        let cornerX = max(x1,x2)
        let cornerY = max(y1,y2)
        let boxWidth = cornerX - originX
        let boxHeight = cornerY - originY

        let box = SKSpriteNode()
        box.size = CGSize(width: boxWidth, height: boxHeight)
        box.color = SKColor.black
        box.position = CGPoint(x:originX, y: originY)
        addChild(box)

        print(x1,y1,x2,y2)
    }
}

3 个答案:

答案 0 :(得分:4)

你在每个函数中重新声明它们。所以他们仍然是该职能的本地人。如你在顶部所做的那样在外部声明它们,然后在函数内部设置值。可能没有必要使用self,但这是一个好主意,因为它可以让你知道你正在玩的变量来自闭包之外。

var x1: CGFloat = 0.0
var y1: CGFloat = 0.0
var x2: CGFloat = 0.0
var y2: CGFloat = 0.0

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

    }
}

//touch ends
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?){
for touch in touches{

print(x1,y1)
let location2 = touch.location(in: self)
self.x2 = location2.x
self.y2 = location2.y
let originX = min(self.x1,self.x2)
let originY = min(self.y1,self.y2)
let cornerX = max(self.x1,self.x2)
let cornerY = max(self.y1,self.y2)
let boxWidth = cornerX - originX
let boxHeight = cornerY - originY

let box = SKSpriteNode()
box.size = CGSize(width: boxWidth, height: boxHeight)
box.color = SKColor.black
box.position = CGPoint(x:originX, y: originY)
addChild(box)

print(self.x1,self.y1,self.x2,self.y2)

答案 1 :(得分:1)

将其更改为函数内没有var。使用var创建一个隐藏类/全局变量的局部变量:

//touch initialized
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

  for touch in touches{
    let location = touch.location(in: self)
    x1 = location.x
    y1 = location.y
    print(x1,y1)

  }
}

答案 2 :(得分:1)

这也使我绊倒了几次。

Swift 3默默地(甚至没有警告)shadows你的属性(或全局 - 我只是用方法名称来猜测它是一个类,用touchesBegan()方法&#39 ; s局部变量:

  

在计算机编程中,变量时会发生变量阴影   在一定范围内宣布(决策块,方法或内部   class)与在外部作用域中声明的变量具有相同的名称。

您可以删除varlet声明以使其正常工作:

x1 = location.x
y1 = location.y

..或者您可以使用self明确限定属性以使其更清晰:

self.x1 = location.x
self.y1 = location.y

围绕这种隐含的阴影行为似乎有一些讨论,这让我觉得它可能会在未来发生变化:https://google.com/search?q=variable+shadow+site:swift.org