SkSpriteNode Position in Universal Game

I create a universal game for all iOS devices in portrait mode using Swift. In GameViewController, I create a scene as follows:

let scene = GameScene(size:CGSize(width: 1536, height: 2048)) scene.scaleMode = .AspectFill 

The background image has a resolution of 1536x2048, and therefore, with the above scale of the Model on the iPad, it is displayed in full size, on the iPhone 6 1152x2048 is displayed with the sides cropped. Works fine on all devices, and only one background image is required. The problem is that if I call size.width or self.frame.size.width, it always returns 1536, even if the actual visible area, for example. One thousand one hundred fifty two.

How to set the position of SkSpriteNode relative to the visible area, so that it will be, for example, 50x50 from the corner on each device?

+6
ios swift sprite-kit
Mar 20 '15 at 7:57
source share
2 answers

How to set the position of SkSpriteNode relative to the visible area, so what will it be, for example, 50x50 from the corner on each device?

The "visible area" is just a view.

So, you can make your position regarding the view , not the scene . I really do a lot in my game, which is universal and works both on OS X and iOS.

In my case, I usually do this for the user interface, so I can have a scaled scene, but I want to set some positions not relative to the scaled scene, but relative to the visible area (i.e. the view).

To do this, you can write a function that converts the coordinates of the view into the corresponding coordinates of the scene.

Here is my function that I use. Note that I subtract the desired y position from the height of the view so that I can process (0,0) as the bottom left, as a sprite set, instead of the top left, as UIKit does.

 func convert(point: CGPoint)->CGPoint { return self.view!.convertPoint(CGPoint(x: point.x, y:self.view!.frame.height-point.y), toScene:self) } 

Here is an example of using this function:

 self.node.position = convert(CGPoint(x: 50, y: 50)) 

This will always force the node position to be (50.50) relative to the view (visible portion of the screen) no matter how your scene is scaled and sized.

+10
Mar 20 '15 at 16:18
source share
— -

I do not think this is really the best approach. You must create a GameScene based on SKView size

 let scene = GameScene(size: self.skView.bounds.size) 

I do not think that you should set one universal size for each device. You must allow the device to set the size of the scenes based on the screen resolution. Then you need to create different images based on the device. 2x, 3x, 2x ~ ipad, etc.

This tutorial is a good place to start: http://www.raywenderlich.com/49695/sprite-kit-tutorial-making-a-universal-app-part-1

+1
Mar 20 '15 at 8:27
source share



All Articles