首页 文章

SpriteKit 部分纹理映射

提问于
浏览
2

是否可以创建仅显示纹理的一部分的SKSpriteNode

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

2 回答

  • 2

    如果你想将纹理分解成较小的纹理块以用作拼图,那么你想要使用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);
    

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

  • 4

    尝试这样的事情:

    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)
            }
        }
    }
    

    Overriden touchesMoved 方法就是因为更好的例子。我在这里做的是:

    • 创建了 SKCropNode

    • 为它添加了一个将被遮罩的纹理

    • 定义了可见区域,即 SKSpriteNode 并将其分配给裁剪节点的掩码属性,这实际上是神奇

    结果如下:

    掩蔽

相关问题