代码之家  ›  专栏  ›  技术社区  ›  Aykut Ucar

SpriteKit部分纹理映射

  •  3
  • Aykut Ucar  · 技术社区  · 8 年前

    是否可以创建一个 SKSpriteNode 只显示纹理的一部分?

    例如,我可以创建一个大小为 100x100 显示大小为的纹理的特定区域 720x720 喜欢 x1=300 x2=400 y1=600 y2=700 ?
    谢谢你的帮助。

    2 回复  |  直到 8 年前
        1
  •  4
  •   Whirlwind    8 年前

    试着这样做:

    import SpriteKit
    import GameplayKit
    
    class GameScene: SKScene {
    
       let visibleArea = SKSpriteNode(color: .black, size: CGSize(width:100,height:100))
    
       let parentNode = SKSpriteNode(color: .white, size: CGSize(width:200, height:200))
    
        override func didMove(to view: SKView) {
    
            let cropNode = SKCropNode()
    
            let texture = SKSpriteNode(imageNamed: "Spaceship")
    
            visibleArea.position = CGPoint(x: 0, y: 100)
            cropNode.maskNode = visibleArea
    
            cropNode.addChild(texture)
    
            addChild(cropNode)
    
    
        }
    
    
        override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
            if let touch = touches.first {
    
                let location = touch.location(in: self)
    
                let previousPosition = touch.previousLocation(in: self)
    
                    let translation = CGPoint(x: location.x - previousPosition.x , y: location.y - previousPosition.y )
    
                    visibleArea.position = CGPoint(x: visibleArea.position.x + translation.x , y: visibleArea.position.y + translation.y)
            }
        }
    }
    

    重写的touchemoved方法只是因为有更好的示例。我在这里做的是:

    • 创建SKCropNode
    • 向其添加纹理,该纹理将被遮罩
    • 定义了可见区域,即SKSpriteNode,并将其分配给裁剪节点的掩码属性,该属性实际上起到了神奇的作用

    结果如下:

    masking

        2
  •  3
  •   Knight0fDragon    8 年前

    如果要将纹理分解为小块纹理,用作拼图块,则需要使用 SKTexture(rect: in texture:)

    下面是一个如何使用它的示例:

    let texture = SKTexture(...)  //How ever you plan on getting main texture
    let subTextureRect = CGRect(x:0,y:0.width:10,height:10) // The actual location and size of where you want to grab the sub texture from main texture
    let subTexture = SKTexture(rect:subTextureRect, in:texture);
    

    现在,您有一块子纹理可用于其他节点。