4

Is it possible to create a SKSpriteNode that displays only a part of a texture?

For example, can I create a square with size 100x100 displaying the specific region of a texture of size 720x720 like from x1=300 to x2=400 and y1=600 to y2=700?
Thanks for your help.

Alessandro Ornano
  • 34,887
  • 11
  • 106
  • 133
Aykut Ucar
  • 615
  • 8
  • 16

2 Answers2

4

Try something like this:

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 method is there just because of better example. What I did here, is:

  • created SKCropNode
  • added a texture to it which will be masked
  • defined visible area which is SKSpriteNode and assigned it to crop node's mask property, which actually does the magic

Here is the result:

masking

Whirlwind
  • 14,286
  • 11
  • 68
  • 157
4

If you want to break up a texture into smaller chunks of textures to be used as puzzle pieces, then you want to use SKTexture(rect: in texture:)

Here is an example of how to use it:

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

You now have a chunk of the sub texture to use in other nodes.

Knight0fDragon
  • 16,609
  • 2
  • 23
  • 44
  • 1
    Thank you! It worked nicely after modifying the rect values. These posts helped too. http://stackoverflow.com/questions/30228104/what-is-happening-to-my-sprite-when-using-initrectintexture. http://stackoverflow.com/questions/21874822/trying-to-use-only-a-portion-of-a-sktexture-using-texturewithrect-intexture. – Aykut Ucar Jan 19 '17 at 19:54