How to create multiple sprites(nodes) with the same texture that will automatically generate a new when one node is removed?

老子叫甜甜 提交于 2019-12-25 09:13:50

问题


I'm trying to create a game where the user can swipe a node and once it's swiped a new node will be created at the bottom of the screen and push all other nodes up, kind of like a reverse Tetris. Here is a very basic image to give you an idea:

I've be able to figure out how to swipe the node off screen but can't seem to figure out how to have all the other nodes move up a row and have a new node created at the bottom. I tried doing an "addChild" for the node I just swiped so it can appear again at the bottom but keep getting an error stating the node already has a parent. Here is my code so far:

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

  }
}

回答1:


As @KnightOfDragon said you can create a copy of your plankWood sprite using .copy() so you could create a function to add a plank kind of like this one:

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

    addChild(newPlank)
}

And then you should have an array of SKSpriteNode holding your planks and you could have a function like this to move your other planks up:

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

Also if you are creating a plankArray you should add this line of code to your addPlank()function: yourPlankArray.append(newPlank)

I hope this helps feel free to ask me any question.



来源:https://stackoverflow.com/questions/39800600/how-to-create-multiple-spritesnodes-with-the-same-texture-that-will-automatica

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!