2017-08-11 58 views
0

我想在屏幕上平均分配n數量的方形SKShapeNodes以創建方形網格。我試圖尋找其他的例子,但我找不到我正在尋找的解決方案,因爲大多數解決方案只關注於水平分佈視圖。Swift/SpriteKit:將SKShapeNodes水平和垂直均勻分佈到網格中

我在for循環中創建方塊,但是我只能讓它們在x或y軸上移動,而不是兩者。下面的例子給我最好的結果,但作爲從代碼只有前兩個方塊是可見預期,第三個被創建關閉屏幕:

amountOfTilesCGFloat組至4

tileSKShapeNode

func addTiles() { 

    let screenWidth = self.view?.frame.size.width 
    tileWidth = screenWidth!/(amountOfTiles/2) 
    tileHeight = tileWidth 

    tileX = 0 
    tileY = 0 

    tileRect = CGRect(x: tileX, y: tileY, width: tileWidth, height: tileHeight) 

    for _ in 0...Int(amountOfTiles) { 

     tile = SKShapeNode(rect: tileRect) 
     tile.position = CGPoint(x: tileX, y: tileY) 
     tile.fillColor = .red 

     addChild(tile) 

     tileX += tileWidth 
     tileY += tileHeight 
    } 
} 

我的猜測是,我不應該在同一時間更新平方的Y和X位置,但我不知道如何解決這個問題。

回答

0

我自己修復了。我刪除了amountOfTiles併爲x和y添加了兩個單獨的CGFloats,我在一個單獨的循環中更新:

func addTiles() { 

     let xAmount:CGFloat = 4 
     let yAmount:CGFloat = 4 

     let screenWidth = self.view?.frame.size.width 
     tileWidth = screenWidth!/(xAmount) 
     tileHeight = tileWidth 

     tileY = 0 

     tileRect = CGRect(x: tileX, y: tileY, width: tileWidth, height: tileHeight) 

     for _ in 0..<Int(xAmount) { 

      tileX = 0 

      for _ in 0..<Int(yAmount) { 

       tile = SKShapeNode(rect: tileRect) 
       tile.fillColor = .red 

       addChild(tile) 

       tile.position = CGPoint(x: tileX, y: tileY) 
       tileX += tileWidth 
      } 

      tileY += tileHeight 
     } 
}