【问题标题】:How to create multiple sprites(nodes) with the same texture that will automatically generate a new when one node is removed?如何创建具有相同纹理的多个精灵(节点),当删除一个节点时会自动生成一个新的?
【发布时间】:2016-09-30 21:54:18
【问题描述】:

我正在尝试创建一个游戏,用户可以在其中滑动节点,一旦滑动节点,将在屏幕底部创建一个新节点并将所有其他节点向上推,有点像反向俄罗斯方块。这是一个非常基本的图像,给你一个想法:

我已经能够弄清楚如何将节点滑出屏幕,但似乎无法弄清楚如何让所有其他节点向上移动一行并在底部创建一个新节点。我尝试为我刚刚刷过的节点做一个“addChild”,这样它就可以再次出现在底部,但不断收到错误消息,指出该节点已经有一个父节点。到目前为止,这是我的代码:

import SpriteKit


let plankName = "woodPlank"

class PlankScene: SKScene {

  var plankWood : SKSpriteNode?


  override func didMove(to view: SKView) {

    plankWood = childNode(withName: "woodPlank") as? SKSpriteNode


    let swipeRight : UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(PlankScene.swipedRight))

    swipeRight.direction = .right

    view.addGestureRecognizer(swipeRight)

  }


  func swipedRight(sender: UISwipeGestureRecognizer) {

    if sender.direction == .right {

    let moveOffScreenRight = SKAction.moveTo(x: 400, duration: 0.5)

    let nodeFinishedMoving = SKAction.removeFromParent()

      plankWood?.run(SKAction.sequence([moveOffScreenRight, nodeFinishedMoving]))

      plankWood?.position = CGPoint(x: 0, y: -250)
      addChild(plankWood!)
    }

  }
}

【问题讨论】:

  • 如果您不移动它 x:400 但假设 x:20,您看到它消失还是仍在屏幕上?如果它停留在屏幕上,则说明它没有正确地从父级中移除。
  • .copy() 让你复制

标签: ios swift sprite-kit skspritenode skscene


【解决方案1】:

正如@KnightOfDragon 所说,您可以使用.copy() 创建plankWood 精灵的副本,这样您就可以创建一个函数来添加类似这样的木板:

func addPlank() {
    let newPlank = plankWood.copy() as! SKSpriteNode
    newPlank.position = CGPoint(x: 0, y: -250) //This should be your first plank position

    addChild(newPlank)
}

然后你应该有一个 SKSpriteNode 数组来支撑你的木板,你可以有这样的功能来向上移动你的其他木板:

func movePlanksUp() {
    for node:SKSpriteNode in yourPlankArray {
        node.runAction(SKAction.moveBy(CGVector(dx: 0, dy: 250), duration: 0.10))
    }
}

此外,如果您要创建 plankArray,则应将此代码行添加到您的 addPlank()function:yourPlankArray.append(newPlank)

我希望这有助于随时问我任何问题。

【讨论】:

  • 这样的作品,但结果有点不稳定。每当我滑动要移除的木板时,addPlank 函数会导致出现一个新的木板,而 movePlansUp 函数会导致刚刚添加的新计划附加到正在从屏幕上滑出的当前木板,从而形成一个巨大的木板。
  • 函数如下所示: func swipedRight(sender: UISwipeGestureRecognizer) { if sender.direction == .right { let moveOffScreenRight = SKAction.moveTo(x: 400, duration: 0.5) let nodeFinishedMoving = SKAction.removeFromParent() plankWood?.run(SKAction.sequence([moveOffScreenRight, nodeFinishedMoving])) self.addPlank() self.movePlanksUp() } }
猜你喜欢
  • 1970-01-01
  • 2023-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多