aignetti aignetti - 6 months ago 16
Swift Question

SpriteKit - Struct for nodes position

i want to make a struct where i declare different positions. I have many nodes which always use the same positions so instead of typing every time the same x-values and y-values i would like to just type positions.p1.

private struct Positions {
let P1 = myGameScene.frame.size.width * 0.05
let P2 = myGameScene.frame.size.width * 0.15
}


Now i get the error:
Instance member frame cannot be used on type myGameScene.
myGameScene is a SKScene.

If i try self. instead of myGameScene i get the error:
Value of type NSObject -> () -> myGameScene has no member frame.


Need help :-(

Answer

It does work

class MyGameScene: SKScene { }

let myGameScene = MyGameScene()

struct XPositions {
    let x0 = myGameScene.frame.size.width * 0.05
    let x1 = myGameScene.frame.size.width * 0.15
}

print(XPositions().x0)

enter image description here

However let me say it's a weird way to solve the problem infact:

  1. You are using a struct instead of an array
  2. You need to create a value of the struct just to access the properties that are the same of every value of Positions
  3. The properties (P1, P2) should be lowercase...

Suggestion

Why don't you just add a computed property to your scene?

class MyGameScene: SKScene {
    lazy var positions: [CGFloat] = {
        let factors: [CGFloat] = [0.15, 0.05]
        return factors.map { $0 * self.frame.size.width }
    }()
}