我正在使用SpriteKit在横向模式下为iPhone创建无尽的跑步者。我是这样设置场景的:
override func viewDidLayoutSubviews() {
let scene = GameScene(size: CGSize(width: 812, height: 375))
let skView = view as! SKView
scene.backgroundColor = UIColor.red
scene.scaleMode = .aspectFill
skView.presentScene(scene)
skView.showsFPS = true
skView.showsNodeCount = true
print("Screen Size: \(GlobalProperties.screenSize.width) x \(GlobalProperties.screenSize.height)")
print("Scene Size: \(scene.size.width) x \(scene.size.height)")
}
我想对播放器进行定位,以使播放器边缘和屏幕右边缘之间的像素数量相同,而与纵横比无关。这是维护设备之间困难的合理做法吗?我有这样的布局设置:
override func didMove(to view: SKView) {
let player = SKSpriteNode(texture: SKTexture(imageNamed: "CuteMelon"))
player.anchorPoint = CGPoint(x: 0.5, y: 0.5)
player.position = CGPoint(x: frame.width - 600, y: frame.midY)
self.addChild(player)
let rect = SKSpriteNode(color: .orange, size: CGSize(width: 550, height: 200))
rect.anchorPoint = CGPoint(x: 1, y: 0.5)
rect.position = CGPoint(x: frame.width-50, y: frame.height/2)
self.addChild(rect)
}
我添加了矩形,以查看两种情况下播放器是否都距右侧600像素(留出50像素的间隙,以确保播放器不会超出边缘)
结果如下:
iPhone XR:https://imgur.com/y6OYHkK可以正常工作
iPhone 8:https://imgur.com/nkrx5By并未将矩形放置在距框架右边界50个像素的位置。
我该怎么做才能解决此问题,或者应该完全采用另一种方式解决它?谢谢
答案 0 :(得分:1)
只需弄清楚场景尺寸和屏幕尺寸之间的差异,然后将相机移动该距离的一半即可。公式abs((sceneWidth - screenWidth * sceneHeight/screenHeight)/2)
可以帮助您。这样做是将屏幕缩放到场景的任何高度,然后从宽度减去两个差值并返回该值的一半。
override func didMove(to view: SKView) {
let widthPadding = abs((self.frame.width - (UIScreen.main.bounds.width * self.frame.height / UIScreen.main.bounds.height )) / 2)
self.camera = self.camera ?? SKCameraNode()
self.camera.position.x += widthPadding
let player = SKSpriteNode(texture: SKTexture(imageNamed: "CuteMelon"))
player.anchorPoint = CGPoint(x: 0.5, y: 0.5)
player.position = CGPoint(x: frame.width - 600, y: frame.midY)
self.addChild(player)
let rect = SKSpriteNode(color: .orange, size: CGSize(width: 550, height: 200))
rect.anchorPoint = CGPoint(x: 1, y: 0.5)
rect.position = CGPoint(x: frame.width-50, y: frame.height/2)
self.addChild(rect)
}