I play fast and try to make a tile-based scrolling game so that the player is central. I have a manager to make it work, but I seem to redraw all the nodes on top of what currently exists, so after a few moves I have 1000 more nodes and the game stops. I assume that I need to delete all old nodes before drawing new ones? I looked at how to do this, for example, to remove children, but then I do not get anything that was done after the transition.
I have included parts that are related to the sprite pattern below.
func placeTile2D(tile:Tile, direction:Direction, position:CGPoint) { let tileSprite = SKSpriteNode(imageNamed: textureImage(tile, direction: direction, action: Action.Idle)) if (tile == hero.tile) { hero.tileSprite2D = tileSprite hero.tileSprite2D.zPosition = 1 } tileSprite.position = position tileSprite.anchorPoint = CGPoint(x:0,y:0) view2D.addChild(tileSprite) } func placeAllTiles2D() { let playerPosCur = playerPosition let playerPCX: Int = (Int(playerPosCur.x)) let playerPCY: Int = (-Int(playerPosCur.y)) var w = 1 var h = 1 for i in (playerPCY - 4) ..< (playerPCY + 4){ let row = tiles[i]; w = 1 for j in playerPCX - 4 ..< playerPCX + 4 { let tile = Tile(rawValue: row[j].0)! let direction = Direction(rawValue: row[j].1)! let point = CGPoint(x: (w*tileSize.width), y: -(h*tileSize.height)) if w == 5 { if h == 5 { self.placeTile2D(Tile.Player, direction: .n, position: point) } } w = w + 1 placeTile2D(tile, direction : direction, position : point) } h = h + 1 } }
- this is what I use to draw tiles around the player, and then below, if I use to change the playerβs position, and then call the placeAllTiles2D () function to redraw based on the new position.
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { if let touch = touches.first { let location = touch.locationInNode(view2D) let touchPos2D = location let moveXR = CGPoint(x:1,y:0) let moveXL = CGPoint(x:-1,y:0) let moveYU = CGPoint(x:0,y:1) let moveYD = CGPoint(x:0,y:-1) let beforeMove = playerPosition var afterMove = CGPoint(x:0,y:0) if touchPos2D.x > self.size.width*3/4 { //Move player to right afterMove = beforeMove + moveXR } if touchPos2D.x < self.size.width*1/4 { //Move Player to left afterMove = beforeMove + moveXL } if touchPos2D.y > -self.size.height/2 { if touchPos2D.x < self.size.width*3/4 && touchPos2D.x > self.size.width*1/4 { //Move PLayer Up afterMove = beforeMove + moveYU } } if touchPos2D.y < -self.size.height/2 { if touchPos2D.x < self.size.width*3/4 && touchPos2D.x > self.size.width*1/4 { //Move Player Down afterMove = beforeMove + moveYD } } playerPosition = afterMove placeAllTiles2D() } }
Any help would be greatly appreciated. Please be careful, my first transition to anything fast!