3
votes

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.

2
You can do this with SKCropNode : developer.apple.com/reference/spritekit/skcropnodeWhirlwind
do you want the entire sprites body to display the full texture, or do you want a sprite with a full texture only display a part of the sprite body?Knight0fDragon
What I am trying to do is a puzzle game; get a texture and create squares from this texture each displaying different parts of the texture.Aykut Ucar
ok I will give you an answerKnight0fDragon

2 Answers

4
votes

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

3
votes

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.