【问题标题】:How to "center" SKTexture in SKSpriteNode如何在 SKSpriteNode 中“居中”SKTexture
【发布时间】:2015-08-17 09:27:41
【问题描述】:

我正在尝试在SpriteKit 中制作拼图游戏。为了让事情变得更容易,我使用了 9x9 方形瓷砖板。每个图块上都有一个childNode,其中包含来自该区域的图像。

但这是我的问题。一块拼图不是完美的正方形,当我将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)

你能给我一些建议吗?

【问题讨论】:

    标签: ios swift sprite-kit


    【解决方案1】:

    如果不了解更多有关您正在使用的棋子纹理,我看不出有一种方法可以正确放置,因为它们都会有所不同。就像这件作品的任何一侧都有一个小头,并且小头的宽度/高度将添加到纹理中。在图片中很难分辨,但即使它没有 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)
    

    希望这是有道理的,不会进一步混淆。

    【讨论】:

    • 整件事是关于如何在正确的位置设置拼图。瞬间,当我将图像剪切成拼图形状时,取 UIBezierPath 帧的剪切中心,然后将其设置为 SKSpriteNode 位置。不过还是谢谢你的回答,以后对我有用。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-22
    • 1970-01-01
    • 1970-01-01
    • 2013-10-04
    • 1970-01-01
    • 1970-01-01
    • 2014-11-07
    相关资源
    最近更新 更多