Sprite kit - how to display half of a sprite / texture / image

I am working on a Sprite Kit project in which I only need to display half of an existing image in some cases.

I tried to make the frame of the sprite smaller, but it just stretches the image.

Is it possible to use a mask or something to only display half of the sprite / image / texture?

+3


source to share


1 answer


So, to show only half of the image, texture, sprite, someone will need to use SKCropNode. The only sane thing to do is crop the sprite you want starting at half, rather than just crop to a predefined size. This can be achieved by setting the mask to node.

1) create a SkSpriteNode with this texture / image:

// Obj-C
SKSpriteNode *skelet = [SKSpriteNode spriteNodeWithImageNamed:imageName];

// Swift
let skelet = SKSpriteNode(imageNamed: imageName)

      

2) create an SKCropNode:

// Obj-C
SKCropNode * cropNode = [SKCropNode node];

// Swift
let cropNode = SKCropNode()

      

3) create a mask



// Obj-C
SKSpriteNode *mask = [SKSpriteNode spriteNodeWithColor:[UIColor blackColor] size:CGSizeMake(skelet.frame.size.width/2, skelet.frame.size.height)];

// Swift
let mask = SKSpriteNode(color: .black, size: CGSize(width: skelet.frame.size.width/2, height: skelet.frame.size.height))

      

** set mask position to half of the desired result (you need half skeleton → set mask position to half "half skeleton")

// Obj-C
mask.position = CGPointMake(skelet.frame.size.width/4, 0);

// Swift
mask.position = CGPoint(x: skelet.frame.size.width/4, y: 0)

      

The division by 4 is that you want the center of the mask not to be in the center of the skeleton node, but to move halfway through the half of the skeleton (a reminder of the mask node works with the default pivot point 0.5 0.5 - so the zero point corresponds to the center skeleton node).

4) add the required elements to the trim node

// Obj-C
[cropNode addChild:skelet];
[cropNode setMaskNode:mask];
[self addChild:cropNode];

// Swift
cropNode.addChild(skelet)
cropNode.maskNode = mask
self.addChild(cropNode)

      

+7


source







All Articles