SpriteKit 部分纹理映射

Posted

技术标签:

【中文标题】SpriteKit 部分纹理映射【英文标题】:SpriteKit partial texture mapping 【发布时间】:2017-01-19 06:31:48 【问题描述】:

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

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

【问题讨论】:

你可以用 SKCropNode 做到这一点:developer.apple.com/reference/spritekit/skcropnode 您是希望整个精灵体显示完整的纹理,还是希望具有完整纹理的精灵只显示精灵体的一部分? 我想做的是一款益智游戏;获取纹理并从该纹理创建正方形,每个显示纹理的不同部分。 好的我给你答案 【参考方案1】:

试试这样的:

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)
        
    

重写 touchesMoved 方法只是因为更好的例子。我在这里所做的是:

已创建 SKCropNode 为其添加了将被遮盖的纹理 定义可见区域,即 SKSpriteNode,并将其分配给裁剪节点的 mask 属性,这实际上起到了作用

结果如下:

【讨论】:

我知道我必须避免这样的命令,但我必须说出来;非常感谢! 我试过了,但无法成功。仍然感谢,因为我在测试时学会了使用裁剪。 非常感谢。也可以实现为普通的ScrollView。【参考方案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);

您现在有一块子纹理可以在其他节点中使用。

【讨论】:

谢谢!修改矩形值后效果很好。这些帖子也有帮助。 ***.com/questions/30228104/…。 ***.com/questions/21874822/….

以上是关于SpriteKit 部分纹理映射的主要内容,如果未能解决你的问题,请参考以下文章

像素区域的OpenGL纹理映射

OpenGL二维纹理映射(2D textures)

OpenGL二维纹理映射(2D textures)

opengl 把纹理映射到立方体的六个面。

OpenGL纹理映射总结

FBO:渲染到纹理,绘制渲染纹理时纹理映射错误