0

好的。这段代码让我发疯。它只是行不通。我收到的唯一消息是“尝试添加一个已经有父节点的 SKNode”。是的,我知道这里有一些讨论,但没有一个给出我需要的解决方案。

这是代码。我真的很感激任何帮助。

import SpriteKit

class MyScene: SKScene {

  let intervalShapeCreation:NSTimeInterval = 2.0  // Interval for creating the next Shape
  let gravitationalAcceleration:CGFloat = -0.5    // The gravitational Y acceleration

  let shapeSequenceAction = SKAction.sequence([
    SKAction.scaleTo(1.0, duration: 0.5),
    SKAction.waitForDuration(2.0),
    SKAction.scaleTo(0, duration: 0.5),
    SKAction.removeFromParent()
    ])

  override init(size: CGSize) {
    super.init(size: size)
  }

  required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
  }

  override func didMoveToView(view: SKView) {
    super.didMoveToView(view)
    addBackground()
    initializeScene()
  }

  // MARK: Level Building
  func initializeScene() {
    self.physicsWorld.gravity = CGVectorMake(0.0, gravitationalAcceleration)
    runAction(SKAction.repeatActionForever(
      SKAction.sequence([SKAction.runBlock(self.createShape),
      SKAction.waitForDuration(intervalShapeCreation)])))
  }

  func addBackground() {
    let backgroundAtlas = SKTextureAtlas(named: "background")
    let background = SKSpriteNode(texture: backgroundAtlas.textureNamed("background"))
    background.position = CGPoint(x: size.width/2, y: size.height/2)
    background.anchorPoint = CGPointMake(0.5, 0.5)
    background.zPosition = -1
    background.name = "background"
    self.addChild(background)
  }

  func createShape() {
    let newShape = sSharedAllPossibleShapes[0]
    print("\n shape creada: \(newShape.name)")
    newShape.position = CGPointMake(size.width / 2, CGFloat( Int.random(fromZeroToMax: 500)))
    self.addChild(newShape)
    newShape.runAction(shapeSequenceAction)
  }

}
4

1 回答 1

1

createShape 实际上并不创建 SKShapeNode。它从 sSharedAllPossibleShapes 数组中获取第一个形状,然后将其作为子元素添加到 self。第二次调用此方法时,形状已经有父对象,无法再次添加。

您必须创建一个新的 SKShapeNode 实例。我看到它的方式在这里你的数组真的需要包含定义形状的 CGPath 对象,而不是节点本身,因为你不能按照你想要的方式重用节点。

于 2014-10-04T07:55:25.063 回答