Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scale/position nodes Swift SpriteKit? Custom View?

I'm working on a game but can't figure out the right way to scale/ position everything. I have a universal app and when I switch from device to device the nodes aren't in the right place everytime. I'm using AspectFill because it sizes my nodes the the right way for each device. The problem is the positioning. I don't know if I'm right in making the conclusion that I need to figure out how to make the view the same size as the screen so that it changes for each device and then positions and scales everything properly, but this is what I've been trying to figure out. I've been trying many different things online and looking at things like how to make a custom view. I've tried to make a rectangle that ha constraints to fill the screen and then setting that rectangle to equal the UIView or SKView. I've tried many different things and looked at many things online but they are either confusing and I don't know if I'm trying them right or they don't pertain to my situation. This is causing a lot of confusion for me and I was hoping someone could help with this issue. I think the issue is that I need to make a custom view that relates to the size of the screen. I don't know if this is possible or what I should be going after. It would be great if someone could clear this up for me.

like image 997
Stevie Thiel Avatar asked Oct 18 '22 22:10

Stevie Thiel


1 Answers

To keep my games universal I make all my nodes sizes and positions dependant on SKScene size

Instead of using hardcoded numbers try using proportions from your SKScene size. For example: Instead of writing this:

node.position = CGPointMake(100, 100)

Write somthing like this:

node.position = CGPointMake(world.frame.size.width / 32 * 16, world.frame.size.height / 18 * 9)

world - SKNode of exactly same size as your SKScene

Same for sizes

let blackSquare = SKSpriteNode(texture: nil, color: UIColor.blackColor(), size: CGSizeMake(world.frame.size.width / 32, world.frame.size.width / 32))

Also GameViewController should look something like this:

override func viewDidLoad() {
    super.viewDidLoad()

    // Configure the view

    let skView = view as! SKView
    skView.multipleTouchEnabled = false

    // Create and configure the scene

    let scene = GameScene(size: skView.bounds.size)
    scene.scaleMode = .AspectFill
    scene.size = skView.bounds.size

    skView.presentScene(scene);
}

Was this helpfull?

like image 106
Darvas Avatar answered Oct 21 '22 16:10

Darvas