Swift Spritekit在多次点击时改变节点的颜色

时间:2017-06-08 19:50:13

标签: swift sprite-kit touchesbegan

我试图让它根据数组中的颜色更改menucene上节点的fillcolor。

我有一个填充了4种颜色的数组,当我按下节点时,它应该根据位置过滤这些颜色。因此,当我点击节点时,它应该将颜色更改为红色,如果我再次点击它会变为绿色,另一个点击会将其更改为紫色,然后再变为蓝色

var colors = [UIColor.blue, UIColor.red, UIColor.green, UIColor.purple]

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first!
    var index = 0
    if changeColor.contains(touch.location(in: self)) {
        index += 1
        changeColor.fillColor = colors[index]
        if index == 3 {
            index = 0
        }
    }
}

然而,这只能读取一个水龙头,我需要它注册多个水龙头

1 个答案:

答案 0 :(得分:2)

在触摸开始函数之外移动索引的初始化,并在更改颜色后递增索引。

var colors = [UIColor.blue, UIColor.red, UIColor.green, UIColor.purple]
var index = 0

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

    if changeColor.contains(touch.location(in: self)) {
        changeColor.fillColor = colors[index]
        index += 1

        if index == colors.count {
            index = 0
        }
    }
}
相关问题