【问题标题】:Swift Spritekit change color of node when tapped multiple times多次点击时,Swift Spritekit会改变节点的颜色
【发布时间】:2017-06-08 19:50:13
【问题描述】:

我正在尝试让它根据数组中的颜色更改菜单场景上节点的填充颜色。

我有一个填充了 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
        }
    }
}

但是,这只读取一次点击,我需要它注册多次点击

【问题讨论】:

  • 我认为它在读取水龙头,但是每次运行此函数时您都会将索引重置为 0,因此您只会看到数组中的第一种颜色。将 var index = 0 移到函数之外应该这样做
  • 更改颜色后也移动索引 += 1 否则您将永远看不到颜色 ins colors[0]
  • 每次输入 touchesBegan() 时都会重置索引。将其移出范围,以便在调用之间持续存在。

标签: swift sprite-kit touchesbegan


【解决方案1】:

将索引的初始化移到 touches begin 函数之外,并在更改颜色后增加索引。

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
        }
    }
}

【讨论】:

  • 另外,将 index 的名称更改为 currentNodeColor 或类似名称。
  • @SteveIves 我确实同意这是一个更好的描述性变量名称,尽管代码不需要工作,但使其更具可读性
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-01
  • 1970-01-01
  • 2018-01-05
  • 2015-09-08
相关资源
最近更新 更多