2015-08-17 34 views
0

我正在試圖在SpriteKit中製作拼圖遊戲。爲了讓事情變得更容易,我使用9x9方磚板。在每個瓷磚上有一張childNode與它的一塊圖像。如何在SKSpriteNode中「中心」SKTexture

但這是開始我的問題。拼圖拼圖塊不是完美的正方形,並且當我將SKTexture應用於節點時,它只是從anchorPoint = {0,0}開始放置。結果並不漂亮,實際上它很可怕。 https://www.dropbox.com/s/2di30hk5evdd5fr/IMG_0086.jpg?dl=0

我設法修復這些瓷磚的右和頂「鉤」,但左側和底側不關心任何事情。

var sprite = SKSpriteNode() 
    let originSize = frame.size 
    let textureSize = texture.size() 
    sprite.size = originSize 
    sprite.texture = texture 
    sprite.size = texture.size() 
    let x = (textureSize.width - originSize.width) 
    let widthRate = x/textureSize.width 
    let y = (textureSize.height - originSize.height) 
    let heightRate = y/textureSize.height 
    sprite.anchorPoint = CGPoint(x: 0.5 - (widthRate * 0.5), y: 0.5 - (heightRate * 0.5)) 
    sprite.position = CGPoint(x: frame.width * 0.5, y: frame.height * 0.5) 
    addChild(sprite) 

你能給我一些建議嗎?

回答

0

我沒有看到一種方法,您可以在不知道更多關於您使用的塊紋理的情況下正確放置貼圖,因爲它們都會不同。就像如果這件作品的任何一面都有一個裸眼,並且寬度的寬度/高度,那麼nob將會添加到紋理上。很難說在照片中,但即使它沒有nob,而是有一個插入它可能會增加不同的尺寸。

不知道紋理是如何創建的,我無法提供幫助。但我確實認爲這個問題始於此。如果是我,我會創建一個帶有附加alpha的正方形紋理,以正確定位該部分。所以紋理的中心總是放在網格上的正方形的中心。

儘管如此,我確實知道將該紋理添加到節點,然後將該節點添加到SKNode會使您的放置位置更順暢。這個技巧只會將這個紋理片正確放置在空的SKNode中。

例如...

let piece = SKSpriteNode() 
    let texturedPiece = SKSpriteNode(texture: texture) 

    //positioning 
    //offset x needs to be calculated with additional info about the texture 
    //for example it has just a nob on the right 
    let offsetX : CGFloat = -nobWidth/2 

    //offset y needs to be calculated with additional info about the texture 
    //for example it has a nob on the top and bottom 
    let offsetY : CGFloat = 0.0 

    texturedPiece.position = CGPointMake(offsetX, offsetY) 
    piece.addChild(texturedPiece) 

    let squareWidth = size.width/2 

    //Now that the textured piece is placed correctly within a parent 
    //placing the parent is super easy and consistent without messing  
    //with anchor points. This will also make rotations nice. 
    piece.position = CGPoint(x: squareWidth/2, y: squareWidth/2) 
    addChild(piece) 

希望這是有道理的,並沒有進一步混淆的東西。

+0

整件事都是關於如何在正確的位置設置拼圖。此刻,當我以拼圖形狀切割圖像時,將剪裁UIBezierPath框架的中心,然後將其設置爲SKSpriteNode位置。但是,無論如何謝謝你的回答,這對我後者會有幫助。 :) –