CCNode没有名为'indexOf'的成员

时间:2016-04-18 12:45:16

标签: swift

我关注Make School's Hoppy Bunny tutorial(链接到此处发布的教程部分)。

时遇到问题
for obstacle in Array(obstacles.reverse()) {
  let obstacleWorldPosition = gamePhysicsNode.convertToWorldSpace(obstacle.position)
  let obstacleScreenPosition = convertToNodeSpace(obstacleWorldPosition)

  //obstacle moved past left side of screen?
  if obstacleScreenPosition.x < (-obstacle.contentSize.width) {
    obstacle.removeFromParent()
    obstacles.removeAtIndex(obstacles.indexOf(obstacle)!)

    //for each removed obstacle, add a new one
    spawnNewObstacle()
  }
}

obstacles.removeAtIndex(obstacles.indexOf(obstacle)!)给我一个错误说

[CCNode] does not have a member named 'indexOf'

我该怎么办?

1 个答案:

答案 0 :(得分:0)

根据提供的信息,我无法看到您indexOf()上使用Array的内容,但您发布的代码非常令人费解。您基本上是在过滤掉障碍,为什么不使用filter()方法呢?以下是使用filter()重写的相同代码:

var numberRemoved = 0

// filter iterates through the Collection and creates a new Collection that contains the items for which the closure returns true
obstacles = obstacles.filter { obstacle in
  let obstacleWorldPosition =  gamePhysicsNode.convertToWorldSpace(obstacle.position)
  let obstacleScreenPosition = convertToNodeSpace(obstacleWorldPosition)

  // if the test in guard is false then perform the code block after else
  // keep the obstacle by returning true
  guard obstacleScreenPosition.x < (-obstacle.contentSize.width) else { return true }

  // remove the obstacle
  obstacle.removeFromParent()
  numberRemoved += 1 // keep a count of removed
  // remove the obstacle by returning false
  return false
}

// add new ones to replace removed ones
for _ in 0..<numberRemoved {
  spawnNewObstacle()
}

尝试使用此代码,它可能会消除您的错误,并且它是执行任务的更好方式。