Andrei L
Andrei L

Reputation: 3651

Swift SKView textureFromNode goes wrong

I started to learn swift by making a game, and encountered some problems.
I am working on a tile game. I created a board of white tiles 6x6 with some holes, and on top of them I created tiles that will move that a coloured.

and then I thought, why not make background tiles an entire sprite, and I go for it, but I encounter The Problem.

As you can see in second image white tiles and coloured tiles do not match their positions. There is a little gap between them. I have an array of positions and tiles are placed at the same position, but when I create the sprite, they are shifted a little bit.

let boardTexture = self.view?.texture(from: backgroundNodes)
boardBackground = SKSpriteNode(texture: boardTexture)

After searching and reading I tried all this but didn't help:

Upvotes: 1

Views: 893

Answers (1)

Daniel K
Daniel K

Reputation: 1129

You should always use

SKView().texture(from: SKNode, crop: CGRect) 

otherwise you are prone to get artifacts. The Crop should typically be

CGRect(x:-size.width/2, y:-size.height/2, width:size.width, height:size.height)

if your node has the default anchor point of 0.5 0.5 (i.e. the center). Using that will give you the size you intend. Also you don't need this

self.view?.texture(from:backgroundNodes)

instead, just say

SKView().texture(from:backgroundNodes)

and you can avoid having to keep a reference somewhere. Also, if you are doing something in an init function of an sknode subclass, there will be no member "view" because it will not have been added to the tree yet.

Upvotes: 4

Related Questions