Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

ios - SkSpriteNode position in universal game

I'm creating universal game for all iOS devices in portrait mode using Swift. In GameViewController I'm creating scene like this:

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

Background image has resolution 1536x2048, and so with above scaleMode on iPad it's displayed in its full size, on iPhone 6 1152x2048 is displayed with sides trimmed. Works perfectly fine on all devices, and only one background image is needed. Problem is that if I call for size.width or self.frame.size.width it always returns 1536, even if the actual visible area is e.g. 1152.

How can I set SkSpriteNode's position relative to visible area, so that it'll be for example 50x50 from the corner on every device?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

How can I set SkSpriteNode's position relative to visible area, so that it'll be for example 50x50 from the corner on every device?

The "visible area" is simply the view.

So you can make your positions relative to the view, and not the scene. I actually do this a lot in my game, which is universal and runs on both OS X and iOS.

In my case I typically do this for the user-interface, so I might 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 view coordinates to the corresponding scene coordinates.

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

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

Here is an example of using this function:

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

This will always force the position of the node to be at (50,50) relative to the view (the visible portion of the screen) regardless of how your scene is scaled and sized.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...